Java批处理

 批处理一次性执行多条sql语句,允许多条语句一次性提交给数据库批量处理,相比单独提交处理,批处理可以大幅度提升大量增、删、改的速度对数据操作的效率有很大的提升

1、没有进行批处理运行结果


2、进行批处理

Statement方法

Connection conn=DBUtil.getConn();
String sql="insert into stu(name,age) values('乐乐',20)";
Statement statement=conn.createStatement();
PreparedStatement ps=conn.prepareStatement(sql);
long begin=System.currentTimeMillis();
for (int i = 0; i <1000; i++) {
	statement.addBatch(sql);//有参数
}
statement.executeBatch();
long end=System.currentTimeMillis();
System.out.println(end-begin);
DBUtil.closeJDBC(null, statement, conn);

PreparedStatement方法

String sql="insert into stu(name,age) values(?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
long begin=System.currentTimeMillis();
for (int i = 0; i <1000; i++) {
	ps.setString(1, "乐乐");
	ps.setInt(2, 22);
	ps.addBatch();//没有参数
}
ps.executeBatch();
long end=System.currentTimeMillis();
System.out.println(end-begin);
DBUtil.closeJDBC(null, ps, conn);


发现效率并没有提高很多,是因为Mysql默认情况下是不支持批处理的,从5.1.13开始,添加一个rewriteBatchedStatements参数。


再次运行,效率比之前高很多




扫描二维码关注公众号,回复: 1432563 查看本文章


猜你喜欢

转载自blog.csdn.net/linbm123/article/details/80554250
今日推荐