本次博客带领大家学习JDBC中批处理的应用和源码分析。
-- 创建数据库
CREATE TABLE admin2(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) NOT NULL,
PASSWORD VARCHAR(32) NOT NULL
);
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);
}
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);
}
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));
}
}