JDBC基本概念
全称:Java Database Connectivity ,是Java和数据库的连接技术
规范:抽象类或接口
java.sql包下的一组接口或抽象类
javax.sql包下的一组接口
好处:
①减轻了开发压力
②提高了代码的维护性
演示JDBC的使用步骤
//步骤1:注册驱动
Class.forName(driver);
//步骤2:获取连接
Connnection connection = DriverManger.getConnection(utl,user,password);
//步骤3:执行查询
String sql = "select * from 表名 where 筛选条件";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet set = ps.executeQuery();
while(set.next()){
int id = set.getInt("bid");
String name = set.getString("bname");
Date borndate = set.getDate("borndate");
char gender = set.getString("bgender").charAt(0);
System.out.println(id+"\t"+name+"\t"+borndate+"\t"+gender);
}
//步骤4:关闭
set.close();
ps.close();
connection.close();
JDBC相关API文档
-
DriverManager 驱动管理类
registDriver(Driver对象):注册驱动,不推荐使用
getConnection(url,user,pwd):获取连接 -
Connnection 连接对象接口
createStatement():生成命令对象
prepareStatement(sql):生成预编译命令对象 -
Statement 命令对象接口
executeUpdate(sql):执行增删改语句,返回受影响的行数
executeQuery(sql):执行查询语句,返回结果集
execute(sql):执行任意sql语句,返回boolean -
PreparedStatement 预编译命令对象接口
executeUpdate():执行增删改语句,返回受影响的行数
executeQuery(sql):执行查询语句,返回结果集
execute(sql):执行任意sql语句,返回boolean
setXX(占位符索引,占位符的值):设置对应索引的占位符的值,类型为XX类型
setObject(占位符索引,占位符的值):设置对应索引的占位符的值,类型为Object类型
占位符索引从1开始 -
ResultSet 结果集对象接口
next():下移一行,返回当前行是否有值
prevlous():上移一行,返回当前行是否有值
getXX(列索引|列名|别名):返回对应列的值,接收类型为XX
getObject(列索引|列名|别名):返回对应列的值,接收类型为Object
PreparedStatement和Statement的区别
关系:
- PreparedStatement和Statement都属于执行sql语句的命令接口,都提供了一系列执行sql语句的方法
- PreparedStatement继承了Statement
区别:
- PreparedStatement不再使用+拼接sql语句,减少了语法错误
- PreparedStatement将sql语句和参数部分实现了分离,提高了语义性和维护性
- PreparedStatement有效的避免了sql注入的问题
- PreparedStatement减少了编译次数,提高了效率
10条sql语句,仅仅只是参数不同
使用Statement,则需要编译10此,执行10此
使用PreparedStatement,只需要编译1次,执行10次
封装JDBCUtils类
功能:
获取连接,释放资源
代码:
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
static String user;
static String password;
static String url;
static String driver;
static {
try{
Properties info = new Properties();
info.load(new FileInputStream("文件地址"));
user = info.getProperty("user");
password = info.getProperty("password");
url = info.getProperty("url");
driver = info.getProperty("driver");
//1.注册驱动
Class.forName(driver);
}catch (Exception e){
throw new RuntimeException(e);
}
}
//获取连接
public static Connection getConnection() {
//2.获取连接
try {
return DriverManager.getConnection(url,user,password);
}catch (Exception e){
throw new RuntimeException(e);
}
}
//释放资源
public static void close(ResultSet set, Statement statement,Connection connection) throws Exception{
try {
if (set!=null){
set.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
事务
JDBC程序中当一个连接对象被创建时,默认情况下是自动提交事务,每次执行一个SQL语句时,如果执行成功,就会向数据库自动提交,而不能回滚。
JDBC程序中为了让多个SQL语句作为一个事务执行:
- 调用Connection对象的setAutoCommit(false);以取消自动提交事务
- 在所有的SQL语句都成功执行后,调用commit():方法返回事务
- 在其中某个操作失败或出现异常时,调用rollback();方法回滚事务
- 若此时Connection没有被关闭,则需要恢复其自动提交状态setAutoCommit(true);
代码:
package JDBC;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Transaction {
Connection connection = null;
PreparedStatement statement = null;
public void testTransaction() throws Exception{
try {
//获取连接
connection = JDBCUtils.getConnection();
//事务步骤1:开启事务
connection.setAutoCommit(false);
//事务步骤2:编写sql语句,并且执行
PreparedStatement statement = connection.prepareStatement("sql语句");
//事务步骤3:结束事务
connection.commit();
}catch (Exception e){
try {
connection.rollback();
}catch (SQLException e1){
e1.printStackTrace();
}
}finally {
JDBCUtils.close(null,statement,connection);
}
}
}
批处理
当需要成批插入或者更新记录。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。
方法:
-
addBath():添加需要批量处理的SQL语句或参数
-
executeBatch():执行批量处理语句
-
clearBatch():清空批处理包的语句
JDBC连接MySQL时,如果要使用批处理功能,请在url中加参数?rewriteBatchedStatements=true
PreparedStatement做批处理插入时使用values(使用value没有效果)