JDBC 批处理
基本介绍
1. 当需要批量插入或更新记录时,可以采用 Java 的批量更新机制,这一机制允许多个语句一次性提交给数据库批量处理(批处理包)。通常情况下批量单独提交处理量更高效
2. 批处理操作和 PreparedStatement 一起搭配使用,可以既减少编译次数,又减少执行次数,效率大大提高
使用前提
如果要使用批处理功能,需要在 url 中加参数:?rewriteBatchedStatements=true
bash
# 添加前
url=jdbc:mysql://localhost:3306/jdbc
# 添加后
url=jdbc:mysql://localhost:3306/jdbc?rewriteBatchedStatements=true相关方法
addBatch():添加需要批量处理的 SQL 语句或参数
以下两个方法配合 if 条件判断语句,自定义批处理的记录条数
executeBatch():执行批量处理语句
clearBatch():清空批处理包的语句
java
if(xxx % 单次批处理的记录条数 == 0){
// 批量执行
preparedStatement.executeBatch();
// 清空批处理包
preparedStatement.clearBatch();
}示例代码
java
public class JDBCUtils_test {
public static void main(String[] args) {
// 定义变量
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
// sql 语句
String sql = "insert into actor values (null,?,'男')";
try {
// 获取连接
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行...");
for (int i = 0; i < 500; i++) {
preparedStatement.setString(1, "john" + (i + 1));
// 添加到批处理包中
preparedStatement.addBatch();
// 自定义处理的批处理的记录数(下方单次处理 100 条记录)
if ((i + 1) % 100 == 0) {
// 批量执行
preparedStatement.executeBatch();
// 清空批处理包
preparedStatement.clearBatch();
}
}
int rows = preparedStatement.executeUpdate();
if (rows > 0) {
System.out.println("执行成功");
} else {
System.out.println("执行失败");
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.close(resultSet, connection, preparedStatement);
}
}
}底层分析
采用 ArrayList 数组
1. 首先创建 ArrayList - elementData => Object[]
2. elementData => Object[] 就会存放我们预处理的 sql 语句
3. 当 elementData 满后, 就按照 1.5 扩容
4. 当添加到指定的值后, 就 executeBatch
5. 批量处理会减少我们发送 sql 语句的网络开销,而且减少编译次数,因此效率提高
java
public void addBatch() throws SQLException {
synchronized(this.checkClosed().getConnectionMutex()) {
if (this.batchedArgs == null) {
this.batchedArgs = new ArrayList();
}
for(int i = 0; i < this.parameterValues.length; ++i) {
this.checkAllParametersSet(this.parameterValues[i], this.parameterStreams[i], i);
}
this.batchedArgs.add(new BatchParams(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths, this.isNull));
}
}