JDBC概述
DBC (Java DataBase Connectivity)是Java数据库连接技术的简称,提供连接各种常用数据库的能力。
JDBC的工作原理
JDBC 核心API
JDBC的开发步骤
Class.forName()加载驱动 > DriverManager 获取Connection连接 > 创建Statement执行SQL语句 > 返回ResultSet 查询结果 > 释放资源
1、加载驱动
2、连接数据库
3、预执行
4、执行SQL并返回结果集
5、释放资源
Connection接口的常用方法
Statement接口的常用方法
ResultSet接口的常用方法
PreparedStatement接口
PreparedStatement接口是Statement的子接口,你可以使用该接口来替换Statement接口。
提高了代码的可 读性和可维护性
提高了SQL语句执行的性能
提高了安全性
查询
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName(“JDBC驱动类”); //1.加载驱动
con=DriverManager.getConnection(URL,数据库用户名,密码);//2.获取Connection 连接对象
String sql = "SELECT username,userpass,nickname FROM users where username=? and userpass=?";
stmt = con.prepareStatement(sql); //3.创建PrepareStatement对象,执行SQL语句
smt.setString(1, “zhangsan”); //4.给参数赋值
smt.setString(2, "0");
rs = stmt.executeQuery();//5.返回ResultSet并查询结果
……
}catch(Exception e){
e.printStackTrace();
}finally{
//6.释放资源
try {if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch(SQLException e) {}
}
添加
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName(“JDBC驱动类”); //1.加载驱动
con=DriverManager.getConnection(URL,数据库用户名,密码);//2.获取Connection 连接对象
String sql = " INSERT INTO student(字段列表) VALUES(值列表) ";
stmt = con.prepareStatement(sql); //3.创建PrepareStatement对象
smt.setString(1, “zhangsan”); //4.给参数赋值
smt.setInt(2, 0);
int row = stmt. executeUpdate();//5.执行SQL语句,返回受影响的行数
……
}catch(Exception e){
e.printStackTrace();
}finally{
//6.释放资源
try {if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch(SQLException e) {}
}
修改
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName(“JDBC驱动类”); //1.加载驱动
con=DriverManager.getConnection(URL,数据库用户名,密码);//2.获取Connection 连接对象
String sql = " UPDATE student SET loginpwd=? WHERE studentno=? AND loginpwd=? ";
stmt = con.prepareStatement(sql); //3.创建PrepareStatement对象
smt.setString(1, “zhangsan”); //4.给参数赋值
smt.setInt(2, 0);
int row = stmt. executeUpdate();//5.执行SQL语句,返回受影响的行数
……
}catch(Exception e){
e.printStackTrace();
}finally{
//6.释放资源
try {if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch(SQLException e) {}
}
删除
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName(“JDBC驱动类”); //1.加载驱动
con=DriverManager.getConnection(URL,数据库用户名,密码);//2.获取Connection 连接对象
String sql = " DELETE FROM student WHERE studentno=? ";
stmt = con.prepareStatement(sql); //3.创建PrepareStatement对象
smt.setString(1, “zhangsan”); //4.给参数赋值
smt.setInt(2, 0);
int row = stmt. executeUpdate();//5.执行SQL语句,返回受影响的行数
……
}catch(Exception e){
e.printStackTrace();
}finally{
//6.释放资源
try {if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch(SQLException e) {}
}