看到jdbc2.0的batch批处理,就自己试试它的性能如何。
1.现在新建一张测试用的表,数据库为oracle,mysql不支持batch批处理,及时在mysql中用了batch,数据库也只是会做普通的处理。
create table batch(id int,name varchar(5))
2.向此表中插入数据。
batch批处理:
PreparedStatement stmt = conn.prepareStatement("insert into batch values(?,'abc')");
stmt.clearBatch();
System.out.println("开始时间:"+System.currentTimeMillis());
for(int i=0;i<500000;i++){
stmt.setInt(1, i);
stmt.addBatch();
}
stmt.executeBatch();
System.out.println("结束时间:"+System.currentTimeMillis());
直接插入处理:
PreparedStatement stmt = conn.prepareStatement("insert into batch values(?,'abc')");
System.out.println("开始时间:"+System.currentTimeMillis());
for(int i=0;i<500000;i++){
stmt.setInt(1, i);
stmt.execute();
}
System.out.println("结束时间:"+System.currentTimeMillis());
当咱们把插入数据量提高到的时候,具体比较见下表
数据量 | 100 | 500 | 5000 | 5万 | 50万 |
一条一条插 | <1s | <1s | ~3s | ~20s | ~240s |
batch批处理 | <1s | <1s | <1s | <1s | ~7s |
上图是我拿自己的笔记本跑出来的,所以说数据还是可信的。由此可见在我们对数据库进行大批量数据操作的时候,能合理的运用batch方法,可以提高很大的工作效率。