java语言基础入门——JDBC(使用Java连接数据库)

4 篇文章 0 订阅

JDBC的全称为JAva Database Connectivity ,即Java数据库连接之意。JDBC是Java用来连接和访问数据的应用编程接口(API),可以通过他完成 一系列的数据库操作。使用JDBC的好处是可以“一次编写,处处运行”,即开发人员不必为了访问不同的数据库编写不同的程序。开发人员只要使用规范的API接口以及标准的sql语句就可以避免直接处理底层数据库驱动程序与相关操作接口的差异性。

JDBC由两层构成:上一层是JDBC  API,该API负责与JDBC驱动程序管理器API进行通信,将各个不同的sql语句发送给他;下面一层是驱动程序管理器API,它与实际连接到数据库的、由供应商数据库驱动程序进行通信,并且返回查询信息,或者执行由查询规定的操作。 因此在进行Java与数据库通信时首先要将供应商提供的数据库驱动程序包含进项目中,其中Mysql的jar下载链接如下,也可去官网下载。链接:http://pan.baidu.com/s/1nv8jpBb 密码:9g3w

JDBC常用类介绍:

1、DriverManager类是JDBC的管理层,作用于用户和驱动程序之间。它跟踪可用的驱动程序,并在数据库和相应驱动程序之间建立连接。另外DriverManager类也处理驱动程序登陆时间限制以及登陆和跟踪消息的显示的等事务。

一般来说Java程序首先使用JDBC API来与JDBC Dirver  Manager 来交互,由JDBC Dirver Manager 载入指定的JDBC驱动程序,以后就可以通过JDBC API 来存取数据库。

2、Connection接口,Connection对象代表特定数据库的连接。通过DriverManager 类的静态方法getConnection()方法可以获取Connection接口的实现类对象。DriverManager类提供的获取Connection实现类对象的方法如下:

(1)static  Connection getConnection (String url)//建立到给定数据库URL的连接

(2)static  Connection getConnection (String url , Properties  info)//建立到给定数据库URL的连接

(3)(1)static  Connection getConnection (String url , String user, String  password)//建立到给定数据库URL的连接

3、Statement接口 , Statement对象用于将SQL语句发送到数据库中,执行对数据库的操作。它有两个子接口:CallableStatement 和 PreparedStatement。

可以通过Connection的相关方法获取Statement对象。具体方法如下:

(1)Statement  createStatement()//创建Statement对象来将SQL语句发送到数据库

(2)Statement createStatement(int  resultSetType, int  resultSetConcurrentcy)//创建Statement对象,该对象将生成具有给定类型和并发性的ResultSet对象

(3)Statement createStatement(int  resultSetType, int  resultSetConcurrentcy,int resultSetHoldability)//创建Statement对象,该对象将生成具有给定的类型、并发性和可保存性的ResultSet对象

4、Statement主要用于执行静态的SQL语句。如果操作动态的SQL语句,则可以使用PreparedStatement来提高执行效率。可以使用Connection的PreparedStatement()方法来建立一个预先编译的SQL语句,其余需要改变的参数使用占位符“?”来代替。等需要指定正真的参数时,再使用相对应的setxxxx(int  parameterIndex,值)的方法,指定“?”处对应的参数值。

可以通过Connection的相关方法获取Statement对象。具体方法如下:

(1)PrepareStatement  prepareStatement(String sql)//创建PrepareStatement 对象来将参数化的SQL语句发送到数据库

(2)PrepareStatement    prepareStatement(String  sql,int autoGeneratedKeys)//创建默认PrepareStatement 对象,该对象能检索自动生成的键

(3)PrepareStatement  prepareStatement(String sql,int[] columnIndexes)//创建能够返回由给定数组指定的自动生成键的默认PrepareStatement对象

(4)PrepareStatement    prepareStatement(String  sql,int resultSetTypes,int resultSetConcurrency)//创建PrepareStatement对象,该对对象生成具有给定类型和并发性的Result对象

(5)PrepareStatement    prepareStatement(String  sql,int resultSetTypes,int resultSetConcurrency ,int  resultSetHoldability)//创建PrepareStatement对象,该对象将生成具有给定类型、并发性和可保存性的Result对象

(6)PrepareStatement    prepareStatement(String  sql,String[]  columnNames)//创建能够返回由给定数组指定的自动生成键的默认PrepareStatement对象

5、ResultSet接口,ResultSet包含符合SQL语句中条件的所有行,并且它通过一套get()方法提供了对这些行中数据的访问,这些get()方法可以访问当前行中的不同列。ResultSet.next()方法用于移动到ResultSet中的下一行,使下一行成为当前行。

可以通过Statement的相关方法获得ResultSet对象。具体方法如下:

(1)execute(String sql)//执行给定的SQL语句,该语句可能返回多个结果

(2)boolean  execute(String sql, String[]  columnNames)//执行给定的SQL语句(该语句可能返回多个结果),并通过驱动程序在给定数组中指示的自动生成的键应用于检索

(3)int []  executeBatch()//将一批命令提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组

(4)ResultSet executeQuery(String sql )//执行给定的SQL语句,该语句返回单个ResultSet对象

(5)int  executeUpdate(String sql)//执行给定的SQL语句,该语句可能为INSERT、UPDATE或DELETE语句,或者不返回任何内容的SQL语句


JDBC操作SQL步骤:

1、导入与SQL相关的包

2、加载JDBC驱动程序

3、提供连接URL

        MySQL的连接URL编写格式为:jdbc:mysql://主机名称:连接端口/数据库名称?参数=值&参数=值&。。。

       Oracle的连接URL编写格式为:jdbc:oracle:thin:@主机名称:端口。。。

       SQL Server  2000 的连接URL编写格式为: jdbc:sqlserver://主机名称:端口:DatabaseName=数据库文件

      Access  2000 的连接URL编写格式为: url:“jdbc:odbc:Driver={Microsoft  Access Driver  (* .mdb)};  DBQ=数据库文件路径”

4、建立一个数据库连接

     要连接数据库,可以向DriverManager要求并获取Connection对象。   Connection是数据库连接的具体代表对象,一个Connection对象就代表一个数据库连接,可以使用DriverManager的getConnection()方法传入指定的连接URL、用户名和密码来获得。

5、创建一个Statement对象

      要执行SQL语句,必须获取Statement对象,他是Java中一个SQL语句的具体代表对象。Statement对象可以通过Connection类的getStatement()方法获得

6、执行SQL语句

     获取Statement对象之后,可以使用Statement对象的以下方法来执行SQL。

     (1)int  executeUpdate(String  sql):执行改变数据库内容的SQL,如insert、delete、update、create table、drop table 等语句,返回本操作影响到的记录数。

     (2)ResultSet  executeQuery(String sql):执行查询数据库的SQL,如select语句,返回查询到的结果集ResultSet对象。

7、处理结果

     执行更新返回的结果是本次操作影响到的记录数。执行查询返回的结果是一个ResultSet对象。

     ResultSet是数据库结果集的数据表。ResultSet对象具有指向当前数据行的光标。最初,光标被置于第一行之前。可以使用ResultSet的next()方法来移动光标到下一行,它会返回true或false,表示是否有下一行数据。

    ResultSet对象上有两种方式可以从当前行获取指定列的值:

         (1)getxxxxx(int    columnIndex)//使用列索引获取值。列从1开始编号,较为高效

         (2)getxxxxx(String  columnLabel)//使用列的名称获取值。

8、关闭JDBC对象

    操作完成后需要把所使用的JDBC对象全部显示关闭,以释放JDBC资源:

    调用ResultSet的close()方法。

    调用Statement的close()方法。

    调用Connection的close()方法。


一个详细设计实例如下:

    数据设计情况如下:

  

create table choicetest(
id smallint,6
profession char(8),
class mediumint,9
class_id int,11
name  char(6),
sex char(2),
phone char(11),
teacher char(5),
choice char(2),
create_name char(10),
create_Date  date,
update_name  char(10),
update_Date date
);

  JDBC基本示例如下:

package address_book;

import java.sql.Date;

public class People {

	private Integer id;
	private String profession;
	private Integer classnum;
	private Integer class_id;
	private String name;
	private String sex;
	private String mobile;
	private String choice;
	private String teacher;
	private String create_name;
	private String update_name;
	private Date create_date;
	private Date update_date;
	private Integer isdel;
	public String getTeacher() {
		return teacher;
	}
	public void setTeacher(String teacher) {
		this.teacher = teacher;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getProfession() {
		return profession;
	}
	public void setProfession(String profession) {
		this.profession = profession;
	}
	public Integer getClassnum() {
		return classnum;
	}
	public void setClassnum(Integer classnum) {
		this.classnum = classnum;
	}
	public Integer getClass_id() {
		return class_id;
	}
	public void setClass_id(Integer class_id) {
		this.class_id = class_id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getChoice() {
		return choice;
	}
	public void setChoice(String choice) {
		this.choice = choice;
	}
	public String getCreate_name() {
		return create_name;
	}
	public void setCreate_name(String create_name) {
		this.create_name = create_name;
	}
	public String getUpdate_name() {
		return update_name;
	}
	public void setUpdate_name(String update_name) {
		this.update_name = update_name;
	}
	public Date getCreate_date() {
		return create_date;
	}
	public void setCreate_date(Date create_date) {
		this.create_date = create_date;
	}
	public Date getUpdate_date() {
		return update_date;
	}
	public void setUpdate_date(Date update_date) {
		this.update_date = update_date;
	}
	public Integer getIsdel() {
		return isdel;
	}
	public void setIsdel(Integer isdel) {
		this.isdel = isdel;
	}
	
}

package address_book;

import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;

public class Connect_MySQL {

	private static final String URL="jdbc:mysql://127.0.0.1:3306/databasetest";
	private static final String  USER="root";
	private static final String  PASSWORD="197069";
	private static Connection connection=null;
 
	static{
		//1、加载驱动程序(反射的方法)
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		//2、连接数据库
		try {
		connection=(Connection) DriverManager.
					getConnection(URL, USER,PASSWORD);//地址,用户名,密码
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConnection(){
		return connection;
	}
	
}

package address_book;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class OperationPeople {

	private static Connection connection=null;
	
	public void addPeople(People people){//增
		connection = Connect_MySQL.getConnection();
		String sql="insert into choicetest "+
			" (profession,class,class_id,name,sex,phone,teacher,choice,create_name,create_Date) "+
				 " values(?,?,?,?,?,?,?,?,?,now())";
		try {
			java.sql.PreparedStatement ptmt=connection.prepareStatement(sql);
			
			ptmt.setString(1, people.getProfession());
			ptmt.setInt(2, people.getClassnum());
			ptmt.setInt(3, people.getClass_id());
			ptmt.setString(4, people.getName());
			ptmt.setString(5, people.getSex());
			ptmt.setString(6, people.getMobile());
			ptmt.setString(7, people.getTeacher());
			ptmt.setString(8, people.getChoice());
			ptmt.setString(9, people.getCreate_name());
		
			ptmt.execute();//执行给定的SQL语句,该语句可能返回多个结果
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
	}
	
	public void delPeople(int id){//删
		connection = Connect_MySQL.getConnection();
		String sql="delete from choicetest where class_id=? ";
		try {
			java.sql.PreparedStatement ptmt=connection.prepareStatement(sql);
			
			ptmt.setInt(1, id);
			
			ptmt.execute();//执行给定的SQL语句,该语句可能返回多个结果
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if (connection != null) {
					connection.close();//关闭connection对象
				}
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
	}
	
	public void updateChoice(People  people){//改
		connection = Connect_MySQL.getConnection();
		String sql=" update choicetest " +
		" set choice=?,update_name=?,update_date=NOW()  "+
				" where class_id=? ";
		try {
			java.sql.PreparedStatement ptmt=connection.prepareStatement(sql);
			ptmt.setString(1,people.getChoice());
			ptmt.setString(2,people.getUpdate_name());
			ptmt.setInt(3,people.getClass_id());
			
			ptmt.execute();//对应于增删改操作
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
		
		
	}
	
	public ArrayList<People> query(){//查
		connection = Connect_MySQL.getConnection();
		Statement statement=null;
		try {
			statement = (Statement) connection.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		ResultSet resultset=null;
		try {
			resultset = statement.executeQuery("select * from choicetest where choice='是'");//SQL语句
		} catch (SQLException e) {
			e.printStackTrace();
		}
		ArrayList<People> pList=new ArrayList<People>();
		People people=null;
		
		try {
			while(resultset.next()){
				people=new People();
				people.setName(resultset.getString("name"));
				people.setClass_id(resultset.getInt("class_id"));
				people.setId(resultset.getInt("id"));
				pList.add(people);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}try {
			if (resultset != null) {
				resultset.close();//关闭resultSet对象
			}
		} catch (SQLException e) {
			e.printStackTrace();		
	}finally {
		try {
			if (connection != null) {
				connection.close();//执行给定的SQL语句,该语句可能返回多个结果
			}
		} catch (SQLException e) {

			e.printStackTrace();
		}
	}
		return pList;
	}
	public People getPeople(int id) {//查一个
		People people2=null;
		connection = Connect_MySQL.getConnection();
		String sql="select * from  choicetest where class_id=?";
		ResultSet resultSet =null;
		try {
			java.sql.PreparedStatement ptmt=connection.prepareStatement(sql);
			
			ptmt.setInt(1,id);
			 resultSet = ptmt.executeQuery();//对应于SQL查询语句
			while(resultSet.next()){
				people2=new People();
				people2.setId(resultSet.getInt("id"));
				people2.setChoice(resultSet.getString("choice"));
				people2.setClass_id(resultSet.getInt("class_id"));
				people2.setClassnum(resultSet.getInt("class"));
				people2.setCreate_date(resultSet.getDate("create_date"));
				people2.setCreate_name(resultSet.getString("create_name"));
				people2.setMobile(resultSet.getString("phone"));
				people2.setName(resultSet.getString("name"));
				people2.setProfession(resultSet.getString("profession"));
				people2.setSex(resultSet.getString("sex"));
				people2.setTeacher(resultSet.getString("teacher"));
				people2.setUpdate_date(resultSet.getDate("update_date"));
				people2.setUpdate_name(resultSet.getString("update_name"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
			try {
				if (resultSet != null) {
					resultSet.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();		
		}finally {
			try {
				if (connection != null) {
					connection.close();//执行给定的SQL语句,该语句可能返回多个结果
				}
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
		return people2; 
	}
}

package address_book;

import java.util.ArrayList;

public class Control {
	
	public static void query(){ //查多个
		OperationPeople operationPeople=new OperationPeople();
		ArrayList<People> pList=	operationPeople.query();
		for (People people: pList) {
			System.out.println(people.getName()+"   "+people.getClass_id()+"   "+people.getId());
		}
	
	}
	
	public static void getPeople(int id) { // 查一个
		OperationPeople operationPeople=new OperationPeople();
		People people=null;
		people=operationPeople.getPeople(id);	
		System.out.println(people.getName()+"   "+people.getClass_id()+"   "+people.getChoice());
	
	}
	
	public static void addPeople(People  people) {  //增加
		OperationPeople operationPeople=new OperationPeople();
		operationPeople.addPeople(people);
	}
	public static void delPeople(int id){ // 删除
		OperationPeople operationPeople=new OperationPeople();
		operationPeople.delPeople(id);
	
	}
	public static void updateChoice(People people){  //更新
		OperationPeople operationPeople=new OperationPeople();
		operationPeople.updateChoice(people);
	}
	

	public static void main(String[] args) {
//		query();
		//getPeople(14250331);
		//delPeople(14250331);
		People people= new People();
		people.setChoice("否");
		people.setUpdate_name("root122223");
		people.setClass_id(14250333);
	//	updateChoice(people);
		people.setClassnum(142503);
		people.setProfession("11");
		people.setMobile("123456789");
		people.setSex("男");
		people.setName("李11");
		people.setCreate_name("root");
		people.setTeacher("韩腾跃");
		addPeople(people);
	
	}

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值