JAVA JDBC batch operations

Batch operations, you can use the batch operations, and increase speed manual submission practices

Batch and manual submission

            // settings do not allow automatic submission of data 
            conn.setAutoCommit ( false ); 
            
            String SQL = "INSERT INTO Goods (name) values (?)" ; 
            PS = conn.prepareStatement (SQL);
             for ( int i = 1; i <= 1000000; I ++ ) { 
                ps.setObject ( . 1, "name_" + I); 
                
                // 1. "save" SQL 
                ps.addBatch (); 
                
                IF (I 500% == 0 ) {
                     // 2. performed BATCH 
                    PS. the executeBatch (); 
                    
                    // 3. empty BATCH 
                    ps.clearBatch (); 
                }
                
            } 
            
            // submit data 
            conn.commit ();

 

 

// bulk insert four ways: automatically set up a connection is not allowed to submit data 
    @Test
     public  void testInsert3 () { 
        Connection Conn = null ; 
        the PreparedStatement PS = null ;
         the try { 
            
            Long Start = System.currentTimeMillis (); 
            
            Conn = JDBCUtils.getConnection ( ); 
            
            // settings do not allow automatic submission of data 
            conn.setAutoCommit ( false ); 
            
            String SQL = "INSERT INTO Goods (name) values ()?" ; 
            PS = conn.prepareStatement (SQL);
             for( Int I =. 1; I <= 1000000; I ++ ) { 
                ps.setObject ( . 1, "name_" + I); 
                
                // 1. "save" SQL 
                ps.addBatch (); 
                
                IF (I 500% == 0 ) {
                     // 2. perform BATCH 
                    ps.executeBatch (); 
                    
                    // 3. empty BATCH 
                    ps.clearBatch (); 
                } 
                
            } 
            
            // submit data 
            conn.commit (); 
            
            Long End = System.currentTimeMillis (); 
            
            the System.out. the println ( "time spent is:" + (End - Start)); // 20000: 83065 - 565 
        }catch (Exception e) {                                //1000000:16086 -- 5114
            e.printStackTrace();
        }finally{
            JDBCUtils.closeResource(conn, ps);
            
        }
        
    }
The complete code

 

Guess you like

Origin www.cnblogs.com/superxuezhazha/p/12408542.html