您的位置:首页 > 博客中心 > 数据库 >

JDBC_批量处理SQL语句

时间:2022-03-15 18:25

使用批处理有两个前提:
1. 首先要MySQL驱动支持批处理(我用的5.17)
2. 配置连接服务器的地址时,在后面加:?rewriteBatchedStatements=true
如:技术图片

  • 相关API:
    • addBatch:将SQL语句添加到批处理包
    • executeBatch:执行批处理包中的SQL语句
    • clearBatch:清空批处理包中的SQL语句

      说明:批处理往往搭配preparedStatement使用:preparedStatement减少编译次数,批处理减少运行次数,效率大大提高

案例:通过批处理向表中插入十万条数据(只要一秒的样子,正常方法要一分钟左右)

/**
 * @author YH
 * @create 2020-03-04 17:33
 */
public class TestBatch {
//注:JDBCUtils为工具类
    @Test
    public void TestBatch(){
        //获取连接
        Connection connection = JDBCUtils.getConnection();
        //执行插入
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement("insert into admin values(null,?,?)");
            for(int i = 1;i <= 100000;i++){ //注意:此处记录条件的值要从1开始,确保被下面的if条件取,避免数据存进了批处理包而未被执行
                statement.setString(1,"name"+i);
                statement.setString(2,""+i);
                //将SQL语句添加到添加到批处理包中
                statement.addBatch();
//                每添加1000次执行并清空一次
                if(i % 1000 == 0){
                    statement.executeBatch();   //执行批处理数据
                    statement.clearBatch();     //清空批处理包
                }
            }
            System.out.println("操作完毕");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JDBCUtils.close(connection,statement,null);
        }
    }
}

本类排行

今日推荐

热门手游