zoukankan      html  css  js  c++  java
  • JDBC_批量处理SQL语句

    使用批处理有两个前提:
    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);
            }
        }
    }
    
  • 相关阅读:
    C. Karen and Game
    BZOJ2134: 单选错位
    BZOJ3562: [SHOI2014]神奇化合物
    BZOJ1084: [SCOI2005]最大子矩阵
    BZOJ5039: [Jsoi2014]序列维护
    BZOJ1798: [Ahoi2009]Seq 维护序列seq
    BZOJ3932: [CQOI2015]任务查询系统
    BZOJ3339: Rmq Problem
    BZOJ3585: mex
    BZOJ4196: [Noi2015]软件包管理器
  • 原文地址:https://www.cnblogs.com/csyh/p/12411877.html
Copyright © 2011-2022 走看看