假如向testone表中插入20000条数据,在不使用快速批量操作时的程序执行需要花费大量时间
然后我们进行优化代码如下
@Test
public void test07() throws SQLException {
long start = System.currentTimeMillis();
Connection connection = JDBCUtils.getconnection();
String sql="insert into testone(name) values(?)";
PreparedStatement statement = connection.prepareStatement(sql);
for (int i = 1; i <= 20000; i++) {
statement.setObject(1,"name"+i);
//攒sql
statement.addBatch();
if(i % 500==0){
//执行
statement.executeBatch();
//清空
statement.clearBatch();
connection.setAutoCommit(false);//事务自动提交关闭
}
}
long end=System.currentTimeMillis();
long time=end-start;
System.out.println("开始时间是"+start+" 结束时间是"+end);
System.out.println("耗时"+time);//耗时95085:没有效果的原因可能是JAR包的问题//5.1.37版本115652//96823无效//108318
}
}
这里需要使用setAutocommit()方法关闭自动事务提交,再使用commit方法提交事务