批处理

133 阅读1分钟
基本介绍
  • 当需要成批插入或者更新记录时,可以采用java的批量更新机制,这一机制允许许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。
  • JDBC的批量处理语句包括下面方法:
    addBatch(): 添加需要批量处理的sql语句或参数
    executeBatch():执行批量处理语句
    clearBatch():清空批处理包的语句
  • JDBC连接Mysql时,如果要试用批处理功能,需要在url中添加 ?rewriteBatchedStatements=true
  • 批处理往往和PreparedStatement一起搭配使用,可以减少变异次数和运行次数,效率大大提升。
@Test
public void useBatch() throws SQLException {
    Connection connection = JDBCUtils.getConnection();
    String sql = "insert into actor values (null,?,?)";
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    long l1 = System.currentTimeMillis();
    System.out.println("开始执行时间="+l1);
    for (int i =  0 ;  i< 500 ; i ++){
        preparedStatement.setString(1,"jack"+i);
        preparedStatement.setInt(2,i);
        //将sql语句加入到批处理包中
        preparedStatement.addBatch();
        //当有1000条记录时再批量执行
        if ( (i+1) % 500 == 0 ){
            preparedStatement.executeBatch();
            //处理完后清空
            preparedStatement.clearBatch();
        }

    }
    System.out.println("消耗时间时间="+(System.currentTimeMillis() - l1));
    JDBCUtils.close(null,preparedStatement,connection);
}