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

    批量处理JDBC语句提高处理速度

    当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率
    JDBC的批量处理语句包括下面两个方法:

    1. addBatch(String):添加需要批量处理的SQL语句或是参数;
    2. executeBatch();执行批量处理语句;

    通常我们会遇到两种批量执行SQL语句的情况:
    多条SQL语句的批量处理;
    一个SQL语句的批量传参;

    多条SQL语句的批量处理

    一个SQL语句的批量传参

    例子:

    1,事务

    2,PreparedStatement 

    3,addBatch(String)+executeBatch()

    来插入巨量数据

    @Test
        public void testBatch(){
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            String sql = null;
            
            try {
                connection = JDBCTools.getConnection();
                JDBCTools.beginTx(connection);
                sql = "INSERT INTO customers VALUES(?,?,?)";
                preparedStatement = connection.prepareStatement(sql);
                Date date = new Date(new java.util.Date().getTime());
                
                long begin = System.currentTimeMillis();
                for(int i = 0; i < 100000; i++){
                    preparedStatement.setInt(1, i + 1);
                    preparedStatement.setString(2, "name_" + i);
                    preparedStatement.setDate(3, date);
                    
                    //"积攒" SQL 
                    preparedStatement.addBatch();
                    
                    //当 "积攒" 到一定程度, 就统一的执行一次. 并且清空先前 "积攒" 的 SQL
                    if((i + 1) % 300 == 0){
                        preparedStatement.executeBatch();
                        preparedStatement.clearBatch();
                    }
                }
                
                //若总条数不是批量数值的整数倍, 则还需要再额外的执行一次. 
                if(100000 % 300 != 0){
                    preparedStatement.executeBatch();
                    preparedStatement.clearBatch();
                }
                
                long end = System.currentTimeMillis();
                
                System.out.println("Time: " + (end - begin)); //569
                
                JDBCTools.commit(connection);
            } catch (Exception e) {
                e.printStackTrace();
                JDBCTools.rollback(connection);
            } finally{
                JDBCTools.releaseDB(null, preparedStatement, connection);
            }
        }
  • 相关阅读:
    Working with WordprocessingML documents (Open XML SDK)
    How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
    Azure:Manage anonymous read access to containers and blobs
    Convert HTML to PDF with New Plugin
    location.replace() keeps the history under control
    On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API
    HTTP Modules versus ASP.NET MVC Action Filters
    解读ASP.NET 5 & MVC6系列(6):Middleware详解
    Content Negotiation in ASP.NET Web API
    Action Results in Web API 2
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/6987005.html
Copyright © 2011-2022 走看看