java 批处理 大量数据的增删改

业务需求:
对一张20万左右的表中的某个字段做一个批量修改
其他方式修改时间太长怕数据库/服务器崩溃
在java中直连mysql 使用批处理的方式增删改
10万数据的修改大概2s左右

直接贴代码

		//定义连接、statement对象
        Connection conn = null;
        PreparedStatement pstm = null;
        private String url = "jdbc:mysql://localhost:3306/0217_mes?useUnicode=true&allowPublicKeyRetrieval=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true&rewriteBatchedStatements=true&useServerPrepStmts=false";
        // rewriteBatchedStatements=true&useServerPrepStmts=false
        //上面URL中 这一段必加,开启批处理
    	private String user = "root";
    	private String password = "123456";
        try {
            //加载jdbc驱动
            Class.forName("com.mysql.jdbc.Driver");
            //连接mysql url:数据库连接地址 
            conn = DriverManager.getConnection(url, user, password);
            //将自动提交关闭
            // conn.setAutoCommit(false);
            //编写sql  此处拼接SQL  增删改都 可以 
            String sql = "INSERT INTO sys_replace VALUES (?,?)";
            //预编译sql
            pstm = conn.prepareStatement(sql);
            //开始总计时
            long bTime1 = System.currentTimeMillis();
			//ma  自己最开始组装好的数据集合
            for (SysMaterial material : ma) {
                //赋值  1代表上面拼接的SQL中的问号,1就是第一个问号,2就是第二个问号
                pstm.setLong(1, material.getSysMaterialId());
                pstm.setString(2, material.getRemark());
                //添加到同一个批处理中
                pstm.addBatch();
            }

            //执行批处理
            pstm.executeBatch();
            conn.close();
            //关闭总计时
            long eTime1 = System.currentTimeMillis();
            //输出
            System.out.println("插入数据共耗时:"+(eTime1-bTime1));
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值