一、JDBC中批处理SQL语句的介绍
二、使用批量处理和非批量处理,进行演示,看具体的耗时区别
public class Batch_ { @Test public void noBatch() throws Exception { Connection connection = JDBCUtils.getConnection(); String sql = "INSERT INTO ADMIN2 VALUES(null,?,?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); System.out.println("开始执行"); long start = System.currentTimeMillis();//开始时间 for (int i = 0; i < 500; i++) { preparedStatement.setString(1, "jack" + i); preparedStatement.setString(2, "666"); preparedStatement.executeUpdate(); } long end = System.currentTimeMillis(); //结束时间 System.out.println("传统的方式 耗时:" + (end - start));//传统的方式 耗时:53942毫秒 //关闭连接 JDBCUtils.close(null, preparedStatement, connection); } //使用批量方式添加数据 @Test public void batch() throws Exception { Connection connection = JDBCUtils.getConnection(); String sql = "INSERT INTO ADMIN2 VALUES(null,?,?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); System.out.println("开始执行"); long start = System.currentTimeMillis();//开始时间 for (int i = 0; i < 500; i++) { preparedStatement.setString(1, "jack" + i); preparedStatement.setString(2, "666"); //将sql语句加入到批处理包中->看源码 /* 1.第一次创建ArrayList 里面有一个对象数组element=>Object 2.elementData => Object[] 就会存放我们预处理的sql语句 3.当elementData满后,就按照1.5倍进行扩容 4.当添加到指定的值后,就executeBatch 5.批量处理会减少我们发送sql语句的网络开销,而且减少编译次数,因此效率提升。 public void addBatch(Object batch) { if (this.batchedArgs == null) { this.batchedArgs = new ArrayList(); } this.batchedArgs.add(batch); } */ preparedStatement.addBatch(); if ((i + 1) % 1000 == 0) { preparedStatement.executeBatch(); //清空一把 preparedStatement.clearBatch(); } } long end = System.currentTimeMillis(); //结束时间 System.out.println("批量的方式 耗时:" + (end - start));//批量的方式 耗时:4毫秒 //关闭连接 JDBCUtils.close(null, preparedStatement, connection); } }