Java batch insert update operation

In the past, it was always said that the efficiency of batch insertion and update is higher than that of non-batch, but the function of batch processing data has never been used. Now because the amount of data to be processed in the project is relatively large, the batch processing function is used, java code as follows:

1.java realizes batch insertion of data:

 Connection conn;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://192.168.0.200:3306/xxx", "root", "root");
            conn.setAutoCommit(false);
            String sql = "insert into test_user (u_name,create_date) value (?,SYSDATE())";
            PreparedStatement prest = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            conn.setAutoCommit(false);

            for (int i = 1; i <= 100; i++) {
                prest.setString(1, "a" + i);
                prest.addBatch ();
            }
            prest.executeBatch();
            conn.commit();


            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

2.java realizes batch update data:

Connection conn;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://192.168.0.200:3306/xxx", "root", "root");
            conn.setAutoCommit(false);

            // Save the current auto-commit mode 
            boolean autoCommit = conn.getAutoCommit();
             // Turn off auto-commit 
            conn.setAutoCommit( false );
             Statement stmt =conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY); 

            for ( int i = 1; i <= num; i++ ) {
                 // Multiple sql statements can be inserted at one time by traversing 
                stmt.addBatch("update test_user set test_user.u_name = ('d"+i+"') where test_user .u_name = ('c"+i+"')" );
            }

            stmt.executeBatch();   
            stmt.clearBatch();
            conn.commit();
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }    

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325206126&siteId=291194637