本次博客带领大家学习JDBC中批处理的应用和源码分析。
批处理的基本介绍
- 当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。
- JDBC的批量处理语句包括下面方法:
- addBatch():添加需要批量处理的SQL语句或参数。
- executeBatch():执行批量处理的语句。
- clearBatch():清空批处理包的语句。
- JDBC连接MySQL时,如果要使用批处理功能,请在url中加参数:rewriteBatchedStatements=true。
- 批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又减少运行次数,效率大大提高。
批处理的应用实例
- 演示向admin2表中添加5000条数据,看看使用批处理耗时多久。
- 注意:需要修改配置文件 jdbc.properties url = jdbc:mysql://localhost:3306/数据库?rewriteBatchedStatements=true
-- 创建数据库
CREATE TABLE admin2(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) NOT NULL,
PASSWORD VARCHAR(32) NOT NULL
);
- 传统方法,添加5000条数据到admin2 传统的方式耗时=438
public void noBatch() throws Exception {
Connection connection = JDBCUtils.getConnection();
String sql = "insert into admin2 values (null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();
for (int i=0;i<5000;i++){
preparedStatement.setString(1,"jack"+i);
preparedStatement.setString(2,"666");
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println("传统的方式耗时="+(end-start));
//关闭连接
JDBCUtils.close(null,preparedStatement,connection);
}
- 使用批量方式添加数据 批量方式 耗时=39
user = root
password = root
url = jdbc:mysql://localhost:3306/ld_db01?rewriteBatchedStatements=true
driver = com.mysql.jdbc.Driver
public void batch() throws Exception{
Connection connection = JDBCUtils.getConnection();
String sql = "insert into admin2 values (null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();
for (int i=0;i<5000;i++){
preparedStatement.setString(1,"jack"+i);
preparedStatement.setString(2,"666");
//将sql 语句加入到批处理包中
preparedStatement.addBatch();
//当有1000条记录时,在批量执行
if((i+1) %1000 ==0){
preparedStatement.executeBatch();
//清空一把
preparedStatement.clearBatch();
}
}
long end = System.currentTimeMillis();
System.out.println("批量方式 耗时="+(end-start));
//关闭连接
JDBCUtils.close(null,preparedStatement,connection);
}
批处理的源码分析
- 第一次就创建 ArrayList - elementData => Object[]。
- elementData => Object[] 就会存放我们预处理的sql语句。
- 当elementData 满后,就按照1.5倍扩容。
- 当添加到指定的值后,就executeBatch()。
- 批量处理会减少我们发送sql语句的网络开销,而且减少编译次数,因此效率提高。
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 PreparedStatement.BatchParams(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths, this.isNull));
}
}