zoukankan      html  css  js  c++  java
  • JDBC 批量处理(插入,删除,更新)

    Connection connection = null;
    try {

    //获取Connection
    connection = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ssm2.0?useUnicode=true", "root", "123456");
    //connection = (Connection) getJdbcTemplate().getDataSource().getConnection();
    //手动提交
    connection.setAutoCommit(false);
    PreparedStatement preparedStatement = null;

    String sqlInsertBatch = "insert into user_opt (userName,optTime) values(?,?)";
    preparedStatement = (PreparedStatement) connection.prepareStatement(sqlInsertBatch);

    for(UserOpt userOpt:userOpts){
    preparedStatement.setString(1, userOpt.getUserName());
    preparedStatement.setDate(2, null);
    preparedStatement.addBatch();
    }
    preparedStatement.executeBatch();

    connection.commit();
    } catch (SQLException e) {
    try {
    connection.rollback();
    } catch (SQLException e1) {
    e1.printStackTrace();
    }
    e.printStackTrace();
    }finally{
    connection.setAutoCommit(true);
    if(connection != null){
    connection.close();
    }
    }

    ps:删除,更新和插入的形式是一样的。

             注意:1. 如果使用了 addBatch() -> executeBatch() 还是很慢,那就得使用到这个参数了

                          rewriteBatchedStatements=true (启动批处理操作)

                          在数据库连接URL后面加上这个参数:      

                              String dbUrl =  "jdbc:mysql://127.0.0.1:3306/ssm2.0?useUnicode=true& rewriteBatchedStatements=true";

                          2. 在代码中,pstmt的位置不能乱放,

                              //必须放在循环体外

                         preparedStatement = conn.prepareStatement("update content set introtext=? where id=?");

                         for(int i=0; i<10000; i++){

                               //放这里,批处理会执行不了,因为每次循环重新生成了pstmt,不是同一个了

                               //preparedStatement = conn.prepareStatement(sql);
                               preparedStatement .setString(1, "abc"+i);
                               preparedStatement .setInt(2, id);
                               preparedStatement .addBatch();//添加到同一个批处理中
                         }

                         preparedStatement .executeBatch();//执行批处理

  • 相关阅读:
    Junit单元测试学习笔记(一)
    perl 函数参数传递与返回值(一)
    Oracle blob字段类型 文件读写实例
    测试沙龙的一些感悟
    常用排序算法选择排序
    perl 哈希(hash)学习笔记(一)
    perl 自定义包/模块的使用(正则表达式匹配email地址和ip)
    常用排序算法冒泡排序
    如何使用excel计算工龄
    畅想(3)打通编程的任督二脉 人工智能
  • 原文地址:https://www.cnblogs.com/krystal0901/p/5521446.html
Copyright © 2011-2022 走看看