一、批处理
1.当需要成批插入或者更新记录时,可以采用Java的批处理更新机制,这个机制允许多条语句一次性提交给数据库批量处理。比单独提交处理更有效率。
2.JDBC的批量处理的方法:
addBatch():添加需要批量处理的SQL语句或参数。
executeBatch():执行批量处理语句。
clearBatch():清空批量处理包的语句。
3.JDBC连接Mysql时,假如需要使用批处理功能,在url中加参数,?rewriteBatchedStatements=true
4.批处理往往和PreparedStatement一起搭配使用,可以减少编译次数,运行次数,提高效率。
配置文件修改
user=root
password=654321
url=jdbc:mysql://localhost:3306/jun_db02?rewriteBatchedStatements=true
driver=com.mysql.jdbc.Driver
-- 创建表
CREATE TABLE admin1(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32)NOT NULL,
`password` VARCHAR(32)NOT NULL
);
SELECT COUNT(*) FROM admin1
DROP TABLE admin1
package com.jun.jdbc.batch;
import com.jun.jdbc.utils.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* 批处理的分析
*/
public class Batch01 {
//传统方法,添加6000条数据到admin1
@Test
public void noBatch() throws Exception {
Connection connection = JDBCUtils.getConnection();
String sql = "insert into admin1 values(null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();//开始时间
for (int i = 0; i < 6000; i++) {//6000执行
preparedStatement.setString(1, "tom" + i);
preparedStatement.setString(2, "111");
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis();//结束时间
System.out.println("传统耗时=" + (end - start));//传统耗时=219260
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
//批量处理添加数据
@Test
public void batch() throws Exception {
Connection connection = JDBCUtils.getConnection();
String sql = "insert into admin1 values(null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();//开始时间
for (int i = 0; i < 6000; i++) {//6000执行
preparedStatement.setString(1, "tom" + i);
preparedStatement.setString(2, "111");
//将sql语句加入到批处理包
/*
源码分析:
1.第一次就创建ArrayList - elementDate => Object[]
2.elementDate ->Object[]就会存放我们预处理的sql语句
3.当elementDate满后,就会按照1.5倍扩容
4.当添加到指定的值后,就executeBatch
5.减少网络的开销和编译次数,效率提高
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));
}
}
*/
preparedStatement.addBatch();
//当有1000条记录,在批量处理
if ((i + 1) % 1000 == 0) {//满1000条
preparedStatement.executeBatch();
//清空
preparedStatement.clearBatch();
}
}
long end = System.currentTimeMillis();//结束时间
System.out.println("批量耗时=" + (end - start));//批量耗时=1243
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}