版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z_x_Qiang/article/details/84672835
批量处理
•当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率
•JDBC的批量处理语句包括下面两个方法:
–addBatch(String):StateMate 添加需要批量处理的SQL语句或是参数;
–addBatch():PrepareStateMate 添加需要批量处理的SQL语句或是参数;
–executeBatch();执行批量处理语句;
•通常我们会遇到两种批量执行SQL语句的情况:
–多条SQL语句的批量处理;
–一个SQL语句的批量传参;
/**
* 测试stateMate的多数据批量处理速度
*/
public void testStateMate(){
Connection connection=null;
Statement statement=null;
try {
connection = JDBCTools.connectDb();
JDBCTools.beginTx(connection);
statement = connection.createStatement();
long starttime=System.currentTimeMillis();
for(int i=0;i<100000;i++){
String sq="insert into CLASSES values('zq"+i+"',18,'男',1000)";
// statement.execute(sq);//消耗时间:59795
//"积攒" SQL
statement.addBatch(sq);
//当 "积攒" 到一定程度, 就统一的执行一次. 并且清空先前 "积攒" 的 SQL
if((i + 1) % 300 == 0){
statement.executeBatch();
statement.clearBatch();
}
}
//若总条数不是批量数值的整数倍, 则还需要再额外的执行一次.
if(100000 % 300 != 0){
statement.executeBatch(); // 消耗时间:62241
statement.clearBatch();
}
long endtime=System.currentTimeMillis();
System.out.println("消耗时间:"+(endtime-starttime));//消耗时间:59795
JDBCTools.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCTools.rollback(connection);
}finally {
JDBCTools.release(connection,statement);
}
}
/**
* 测试preperStateMate普通插入的速度;
*/
public void testPreperStateMate(){
Connection connection=null;
PreparedStatement statement=null;
try {
connection = JDBCTools.connectDb();
JDBCTools.beginTx(connection);
String sq="insert into CLASSES values(?,?,?,?)";
statement = connection.prepareStatement(sq);
long starttime=System.currentTimeMillis();
for(int i=0;i<100000;i++){
statement.setString(1,"zq"+i);
statement.setInt(2,18);
statement.setString(3,"男");
statement.setInt(4,100);
// statement.executeUpdate(); //消耗时间:29160
//"积攒" SQL
statement.addBatch();
//当 "积攒" 到一定程度, 就统一的执行一次. 并且清空先前 "积攒" 的 SQL
if((i + 1) % 300 == 0){
statement.executeBatch();
statement.clearBatch();
}
}
//若总条数不是批量数值的整数倍, 则还需要再额外的执行一次.
if(100000 % 300 != 0){
statement.executeBatch(); // 消耗时间:237
statement.clearBatch();
}
long endtime=System.currentTimeMillis();
System.out.println("消耗时间:"+(endtime-starttime));
JDBCTools.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCTools.rollback(connection);
}finally {
JDBCTools.release(connection,statement);
}
}