1.JDBC简介
JDBC是数据库链接的纽带,全称是Java Database Connectivity。统一数据库接口。
对于不同的数据库,要用不同的JDBC类库。面向JAVA的一端接口是统一的。
2.JDBC编程步骤
1.Load the Driver,即实例化引入Jar里面的Driver
1.Class.forName() 或者 new ***;
2.实例化时自动向DriverManager注册,DriverManager是负责数据库链接的大管家
3.要捕获ClassNotFound的异常。
2.Connect to the DataBase
1.写法: Connection conn = DriverManager.getConnection();
传入的是sql的URL地址和账户密码
3.Execute the SQL
1.写法: Statement stmt = Connection.CreateStatememt();
2.Statement.executeQuery()执行查询,返回时一个结果集:ResultSet
3.Statement.executeUpdate()
4.Retrie the result data
1.循环取得结果while(rs.next)
5.show the result data
1.将数据库中的各种类型转化为Java中的类型(get***方法)
6.close
1.close the resultset
1.close the statement
1.close the connection
3.例子:Java与mysql连接
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=root&password=root");
stmt = conn.creatStatement();
rs - stmt.excuteQuery("selcet * from dept");
while(rs.next()){
System.out.println(rs.getString("deptno"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException ex){
}finally{
try{
if(rs != null){
rs.close();
rs = null;
}
if(stmt != null){
stmt.close();
stmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
1.实例化jdbc.Driver
2.Connection表示要与数据库中哪个数据库做链接
3.Statement是用来执行数据库操作的接口,在已经建立的链接的基础上,向数据库发送sql语句
4.ResultSet是获取执行的结果
5.最终要把各个实例关闭