本文主要讲述,面对多个sql语句【增,删,改】的执行,如何加快执行速度?

传统方法:

public class jdbcBat_ {
    // 同时处理多条数据【原始方法】
    @Test
    public void test1(){
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement preStatement = null;
        String sql = "insert into admin2(name,pwd) values(?,?)";
        try {
            preStatement = connection.prepareStatement(sql);
            long start = System.currentTimeMillis();
            for(int i = 0;i<5000;i++){
                // 处理5000条sql语句
                preStatement.setString(1,"Tom"+i);
                preStatement.setString(2,"123"+i);
                preStatement.executeUpdate();
            }
            long end = System.currentTimeMillis();
            System.out.println("执行时间: "+(int) (end-start));
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.Close(null,preStatement,connection);
        }
    }
}

运行时间:

执行时间: 11393 //ms

使用批处理,即批量处理sql语句,不是一次执行完成,分批次:

在此之前,需要进行如下设置,

url=jdbc:mysql://localhost:3306/hspdb02?rewriteBatchedStatements=true

使得批处理语句可以执行,否则无效。

public class jdbcBat_ {
    // 处理多条数据,使用批处理
    @SuppressWarnings({"all"})
    @Test
    public void test2(){
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement preStatement = null;
        String sql = "insert into admin2(name,pwd) values (?,?)";
        try{
            preStatement = connection.prepareStatement(sql);
            long start = System.currentTimeMillis();
            for(int i = 0;i<5000;i++){
                // 处理5000条sql语句
                preStatement.setString(1,"Tom"+i);
                preStatement.setString(2,"123"+i);
                preStatement.addBatch();
                if((i+1)%1000 == 0){
                    preStatement.executeBatch();
                    preStatement.clearBatch();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("执行时间: "+(int) (end-start));
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.Close(null,preStatement,connection);
        }
    }
}

重点语句:

if((i+1)%1000 == 0){
        preStatement.executeBatch();
        preStatement.clearBatch();
}

每当累计到1000条sql语句时,执行一次,注意执行完成之后,需要清理之前的sql语句。

运行结果:

执行时间: 148

可见使用了批处理,确实加快了执行多行sql语句的速度。