1、Statement批处理
当你有10条SQL语句要执行时,一次向服务器发送一条SQL语句,这样做的效率上极差,处理的方案是使用批处理,即一次向服务发送多条SQL语句,然后由服务器一次性处理。
批处理只针对更新(增删改)语句,批处理与查询无关。
可以多次调用Statement类的addBatch(String sql)方法,把需要执行的所有SQL语句添加到一个“批”中,然后调用Statement类的excuteBatch()方法来执行当前“批中的语句”。
- void addBatch(String sql):添加一条语句到“批”中。
- int[] excuteBatch():执行“批”中所有的语句,返回值表示每条语句所影响的行数据;
- void clearBatch():清空“批”中的所有语句
2、PreparedStatement批处理
PreparedStatement的批处理有所不同,因为每个PreparedStatement对象都绑定一条SQL模板。所以向PreparedStatement中添加的不是SQL语句,而是给“?”赋值。
1 public class Demo5 { 2 /* 3 * pstmt对象内部有集合 4 * 1、用循环疯狂向pstmt中添加sql参数,它自己有模板, 5 * 使用一组参数与模板就可以匹配一条sql语句 6 * 2、调用它的执行批方法,完成向数据库发送。 7 * */ 8 @Test 9 public void fun1() throws Exception { 10 /* 11 * pstmt 12 * */ 13 Connection con = JdbcUtils.getConnection(); 14 String sql = "INSERT INTO t_user VALUES (?,?)"; 15 PreparedStatement pstmt = con.prepareStatement(sql); 16 for (int i = 0; i < 10000; i++) { 17 pstmt.setInt(1,i+1); 18 pstmt.setInt(2,i); 19 pstmt.addBatch();//添加批,这一组参数就保存到集合中; 20 } 21 long start = System.currentTimeMillis(); 22 pstmt.executeBatch();//执行批处理; 23 long end = System.currentTimeMillis(); 24 System.out.println(end-start); 25 } 26 }
打开批处理
MySQL的批处理也需要通过参数来打开:rewriteBatchedStatements=true,如
url = jdbc:mysql://localhost:3306/mydb1?rewriteBatchedStatements=true
效果:
- 批处理开启前耗时:140794ms
- 批处理开启后耗时:174ms