原文参考https://stackoverflow.com/questions/2993251/jdbc-batch-insert-performance

问题描述:

当有数百万的数据需要insert的时候,如何改善性能呢?


   // Disable auto-commit
   connection.setAutoCommit(false);

   // Create a prepared statement
   String sql = "INSERT INTO mytable (xxx), VALUES(?)";
   PreparedStatement pstmt = connection.prepareStatement(sql);

   Object[] vals=set.toArray();
   for (int i=0; i<vals.length; i++) {
       pstmt.setString(1, vals[i].toString());
       pstmt.addBatch();
   }

   // Execute the batch
   int [] updateCounts = pstmt.executeBatch();
   System.out.append("inserted "+updateCounts.length);

通过使用batch以后,执行时间依然很长。

最佳答案:

mysql数据库通过设置参数rewriteBatchedStatements=true来达到目的。

jdbc:mysql://host:3306/db?rewriteBatchedStatements=true

原理

rewriteBatchedStatements=true是如何提升效率的呢?“It does so by rewriting of prepared statements for INSERT into multi-value inserts when executeBatch()”(Source)。这句话的意思是,当每次使用executeBatch() 的时候,不是发送n条insert到mysql。而是发送1条insert语句和多个值到mysql。

INSERT INTO X VALUES (A1,B1,C1)
INSERT INTO X VALUES (A2,B2,C2)
...
INSERT INTO X VALUES (An,Bn,Cn)

上述多条语句取而代之:

INSERT INTO X VALUES (A1,B1,C1),(A2,B2,C2),...,(An,Bn,Cn)

你可以设置mysql日志记录参数 (by SET global general_log = 1) ,来通过日志文件查看发送到mysql server的每一个sql语句。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐