zoukankan      html  css  js  c++  java
  • JDBC--批量处理

    1、当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理,这样可以提高处理速度。

    2、JDBC的批量处理语句包括两个方法:

    --1)addBatch(String):添加需要批量处理的sql语句或参数;

    --2)executeBatch();执行批量处理语句;

    3、通常遇到以下两种情况时需要批量执行sql语句:

    --1)多条sql语句的批量处理:

    --2)一个sql语句的批量传参。

    4、实例

    public void testBatch(){
        Connection conn = null;
        PreparedStatement ps = null;
        String sql = "INSERT INTO customers values(?, ?, ?)";
        try{
            conn = JDBCUtils.getConnection();
            JDBCUtils.startTransaction(conn);
            
            ps = conn.prepareStatement(sql);
            Date date = new Date(new java.util.Date().getTime());
            long start = System.currentTimeMillis();
            for(int i = 0; i < 100000; i++){
                ps.setInt(1, i + 1);
                ps.setString(2, "name_" + i);
                ps.setDate(3, date);
                
                ps.addBatch();
                
                if((i + 1) % 300 == 0){
                    ps.executeBatch();
                    ps.clearBatch();
                }
            }
            ps.executeBatch();
            ps.clearBatch();
            long end = System.currentTimeMillis();
            System.out.println("Time: " + (end - start));
            
            JDBCUtils.commit(conn);
            
        }catch(Exception e){
            e.printStackTrace();
            JDBCUtils.rollback(conn);
        }finally{
            JDBCUtils.release(conn, ps, null);
        }
    }
  • 相关阅读:
    Qt支持中文显示
    C/C++ 知识点---LIB和DLL的区别与使用(网摘)
    Inno Setup
    C/C++ 知识点---字符串函数
    es5 JSON对象
    Es567严格模式
    mysql常用命令
    promise 获取文件内容
    postman连接不了localhost问题解决
    node---处理post请求
  • 原文地址:https://www.cnblogs.com/tengtao93/p/4986191.html
Copyright © 2011-2022 走看看