java mysql 批量處理

使用JDBC連接MySQL數據庫進行數據插入的時候,特別是大批量數據連續插入(10W+),如何提高效率呢?

在JDBC編程接口中Statement 有兩個方法特別值得注意:

void addBatch() throws SQLException
Adds a set of parameters to this PreparedStatement object's batch of commands.

int[] executeBatch() throws SQLException
Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts. The int elements of the array that is returned are ordered to correspond to the commands in the batch, which are ordered according to the order in which they were added to the batch. 

通過使用addBatch()和executeBatch()這一對方法可以實現批量處理數據。

不過值得注意的是,首先需要在數據庫鏈接中設置手動提交,connection.setAutoCommit(false),然後在執行Statement之後執行connection.commit()。
  1. package cyl.demo.ipsearcher;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. import java.sql.Connection;  
  8. import java.sql.DriverManager;  
  9. import java.sql.PreparedStatement;  
  10. import java.sql.SQLException;  
  11.   
  12. public class DbStoreHelper {  
  13.   
  14.     private String insert_sql;  
  15.     private String charset;  
  16.     private boolean debug;  
  17.   
  18.     private String connectStr;  
  19.     private String username;  
  20.     private String password;  
  21.   
  22.     public DbStoreHelper() {  
  23.         connectStr = "jdbc:mysql://localhost:3306/db_ip";  
  24.         // connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true";  
  25.         insert_sql = "INSERT INTO tb_ipinfos (iplong1,iplong2,ipstr1,ipstr2,ipdesc) VALUES (?,?,?,?,?)";  
  26.         charset = "gbk";  
  27.         debug = true;  
  28.         username = "root";  
  29.         password = "***";  
  30.     }  
  31.   
  32.     public void storeToDb(String srcFile) throws IOException {  
  33.         BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), charset));  
  34.         try {  
  35.             doStore(bfr);  
  36.         } catch (Exception e) {  
  37.             e.printStackTrace();  
  38.         } finally {  
  39.             bfr.close();  
  40.         }  
  41.     }  
  42.   
  43.     private void doStore(BufferedReader bfr) throws ClassNotFoundException, SQLException, IOException {  
  44.         Class.forName("com.mysql.jdbc.Driver");  
  45.         Connection conn = DriverManager.getConnection(connectStr, username,password);  
  46.         conn.setAutoCommit(false); // 設置手動提交  
  47.         int count = 0;  
  48.         PreparedStatement psts = conn.prepareStatement(insert_sql);  
  49.         String line = null;  
  50.         while (null != (line = bfr.readLine())) {  
  51.             String[] infos = line.split(";");  
  52.             if (infos.length < 5)   continue;  
  53.             if (debug) {  
  54.                 System.out.println(line);  
  55.             }  
  56.             psts.setLong(1, Long.valueOf(infos[0]));  
  57.             psts.setLong(2, Long.valueOf(infos[1]));  
  58.             psts.setString(3, infos[2]);  
  59.             psts.setString(4, infos[3]);  
  60.             psts.setString(5, infos[4]);  
  61.             psts.addBatch();          // 加入批量處理  
  62.             count++;              
  63.         }  
  64.         psts.executeBatch(); // 執行批量處理  
  65.         conn.commit();  // 提交  
  66.         System.out.println("All down : " + count);  
  67.         conn.close();  
  68.     }  
  69.   
  70. }  

執行完成以後:
  1. All down : 103498  
  2. Convert finished.  
  3. All spend time/s : 47  
一共10W+,執行時間一共花費 47 秒.

這個效率仍然不高,似乎沒有達到想要的效果,需要進一步改進。
在MySQL JDBC連接字符串中還可以加入參數,
rewriteBatchedStatements=truemysql默認關閉了batch處理,通過此參數進行打開,這個參數可以重寫向數據庫提交的SQL語句,具體參見:http://www.cnblogs.com/chenjianjx/archive/2012/08/14/2637914.html
useServerPrepStmts=false如果不開啓(useServerPrepStmts=false),使用com.mysql.jdbc.PreparedStatement進行本地SQL拼裝,最後送到db上就是已經替換了?後的最終SQL.

在此稍加改進,連接字符串中加入下面語句(代碼構造方法中去掉註釋):
connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true";

再次執行如下:
  1. All down : 103498  
  2. Convert finished.  
  3. All spend time/s : 10  
同樣的數據量,這次執行只花費了10秒 ,處理效率大大提高.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章