MySQL使用Batch批量處理

壹頁書發表於2014-04-29
使用MySQL的Batch批量處理,
JDBC驅動版本需要5.1.13或以上
測試使用的JDBC驅動版本:mysql-connector-java-5.1.30-bin



測試表結構如下:
CREATE TABLE test (
  id int(11) DEFAULT NULL,
  name varchar(20) DEFAULT NULL
) ENGINE=InnoDB 

首先使用普通的方式插入100萬條資料,使用時間81948毫秒
程式如下:

  1. public class Test {
  2.     public static void main(String[] args) throws ClassNotFoundException,
  3.             SQLException {
  4.         long start = System.currentTimeMillis();
  5.         Class.forName("com.mysql.jdbc.Driver");
  6.         Connection connection = DriverManager
  7.                 .getConnection(
  8.                         "jdbc:mysql://127.0.0.1:3306/xx",
  9.                         "xx", "xx");

  10.         connection.setAutoCommit(false);
  11.         PreparedStatement cmd = connection
  12.                 .prepareStatement("insert into test values(?,?)");
  13.         
  14.         for (int i = 0; i < 1000000; i++) {
  15.             cmd.setInt(1, i);
  16.             cmd.setString(2, "test");
  17.             cmd.executeUpdate();
  18.         }
  19.         connection.commit();
  20.         
  21.         cmd.close();
  22.         connection.close();
  23.         
  24.         long end = System.currentTimeMillis();
  25.         System.out.println(end - start);
  26.     }
  27. }
使用批量處理,僅用7189毫秒,提升效果非常明顯。
程式如下:

  1. public class Test {
  2.     public static void main(String[] args) throws ClassNotFoundException,
  3.             SQLException {
  4.         long start = System.currentTimeMillis();
  5.         Class.forName("com.mysql.jdbc.Driver");
  6.         Connection connection = DriverManager
  7.                 .getConnection(
  8.                         "jdbc:mysql://127.0.0.1:3306/xx?rewriteBatchedStatements=true",
  9.                         "xx", "xx");

  10.         connection.setAutoCommit(false);
  11.         PreparedStatement cmd = connection
  12.                 .prepareStatement("insert into test values(?,?)");
  13.         
  14.         for (int i = 0; i < 1000000; i++) {
  15.             cmd.setInt(1, i);
  16.             cmd.setString(2, "test");
  17.             cmd.addBatch();
  18.             if(i%1000==0){
  19.                 cmd.executeBatch();
  20.             }
  21.         }
  22.         cmd.executeBatch();
  23.         connection.commit();
  24.         
  25.         cmd.close();
  26.         connection.close();
  27.         
  28.         long end = System.currentTimeMillis();
  29.         System.out.println(end - start);
  30.     }
  31. }
與Oracle不同的是,需要新增下面的引數,才可以使用批量處理,否則還是使用逐條處理的方式。
rewriteBatchedStatements=true

開啟MySQL的查詢日誌general_log,發現如下SQL
INSERT INTO test
VALUES (11, 'test'), (12, 'test'), (13, 'test')......


相對Oracle的批量處理,MySQL需要JDBC引數顯式開啟,並且對於JDBC驅動的版本也有要求。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1151785/,如需轉載,請註明出處,否則將追究法律責任。

相關文章