1. 程式人生 > >mysql批量插入更新加引數rewriteBatchedStatements

mysql批量插入更新加引數rewriteBatchedStatements

測試環境:mysql-connector-java-5.1.34.jar ;
jdbc:mysql://192.168.21.103:3306/yzhs?rewriteBatchedStatements=true
測試程式碼
1、不使用jdbc的addBatch\executeBatch

int size=100000;
    private void noBatch(){
        JDBCHelper jdbc=JDBCHelper.getInstance();
        Connection conn=jdbc.getConnection();
        try {
            conn.setAutoCommit(false
); PreparedStatement prep=conn.prepareStatement("insert into temp_ban_list() values(?)"); long a=System.currentTimeMillis(); for (int i = 0; i < size; i++) { prep.setInt(1, i); prep.execute(); } conn.commit(); long
b=System.currentTimeMillis(); System.out.println("MySql非批量插入10萬條記錄用時"+ (b-a)+" ms"); } catch (SQLException e) { e.printStackTrace(); } } /* * 結果 * MySql非批量插入10萬條記錄用時51657 ms * MySql非批量插入10萬條記錄用時49765 ms */

2、使用jdbc的addBatch\executeBatch

private void batch(){
        JDBCHelper jdbc=JDBCHelper.getInstance();
        Connection conn=jdbc.getConnection();
        try {
            conn.setAutoCommit(false);    
            PreparedStatement prep=conn.prepareStatement("insert into temp_ban_list() values(?)");
            long a=System.currentTimeMillis();  
            for (int i = 0; i < size; i++) {
                prep.setInt(1, i);
                prep.addBatch();
            }
            prep.executeBatch();
            conn.commit();
            long b=System.currentTimeMillis(); 
            System.out.println("MySql批量插入10萬條記錄用時"+ (b-a)+" ms");  
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /*
     * 結果
     * MySql批量插入10萬條記錄用時1040 ms
     * MySql批量插入10萬條記錄用時1097 ms
     * 
     * 去掉引數,結果
     * MySql批量插入10萬條記錄用時91629 ms
     */

結論:使用jdbc的addBatch\executeBatch時url要加引數rewriteBatchedStatements=true