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();//执行批处理

  • 相关阅读:
    struct 结构体解析(原)
    C++标准编程:虚函数与内联
    基于 IOCP 的通用异步 Windows Socket TCP 高性能服务端组件的设计与实现
    直接用编译器按ctrl+F5运行和双击运行结果不一样
    驱动编译的时候注意编译工程选项
    驱动编译的时候注意编译工程选项
    'ddkbuild.cmd' 不是内部或外部命令,也不是可运行的程序
    'ddkbuild.cmd' 不是内部或外部命令,也不是可运行的程序
    NtOpenProcess被HOOK,跳回原函数地址后仍然无法看到进程
    NtOpenProcess被HOOK,跳回原函数地址后仍然无法看到进程
  • 原文地址:https://www.cnblogs.com/krystal0901/p/5521446.html
Copyright © 2011-2022 走看看