当前位置:   article > 正文

JAVA对MYSQL数据库进行批量操作,addBatch(),executeBatch()方法_mysql connector batch

mysql connector batch

最近要做一个批处理插入数据的,但是试了批处理的代码发现没有效果,很纳闷啊。但是之前在学习JDBC操作Mysql批处理的时候,记得要在数据库url中的参数加配置的,但是忘了。网速搜居然不容易搜出来,我也是醉了,难道这么重要的参数都不重视?于是就看到这一篇,感谢博主。至于这个参数就是“rewriteBatchedStatements=true”这个对批处理很大影响,没有它就相当于没有批处理。


有人说MySQL的JDBC驱动,不是真正支持批量操作的,就算你在代码中调用了批量操作的方法,MySql的JDBC驱动也是按照一般操作来处理的。

但其实并非如此,Mysql 是有特殊的方式优化整个batch insert 结果的。

可不可以先假设 batch 的方式与非batch一样,每一条insrt语句事实上均是单独发往服务器的呢?

浏览下源代码吧。 

好多兄弟都描述了源代码,直接从那几个类入手吧,事实上关键的类是这个 com.mysql.jdbc.PreparedStatement 

先看了其中的 addBatch 方法,没有任何问题,只是将语句添加进入一个 List 中保存。 

那么 executeBatch 呢? 

再贴一下吧, 关键看其中的这部分,顺带说一下, 这个mysql-jdbcdriver的源代码是 5.1.13的 

[java]  view plain  copy
  1. try {     
  2.     clearWarnings();     
  3.     
  4.     if (!this.batchHasPlainStatements     
  5.             && this.connection.getRewriteBatchedStatements()) {     
  6.              
  7.              
  8.         if (canRewriteAsMultiValueInsertAtSqlLevel()) {     
  9.             return executeBatchedInserts(batchTimeout); //执行路径之一     
  10.         }     
  11.              
  12.         if (this.connection.versionMeetsMinimum(410)      
  13.                 && !this.batchHasPlainStatements     
  14.                 && this.batchedArgs != null      
  15.                 && this.batchedArgs.size() > 3 /* cost of option setting rt-wise */) {     
  16.             return executePreparedBatchAsMultiStatement(batchTimeout); //执行路径之二     
  17.         }     
  18.     }     
  19.     
  20.     return executeBatchSerially(batchTimeout); //执行路径之三     
  21. finally {     
  22.     clearBatch();     
  23. }   

其实最终,executeBatch 的执行路径有三种可能。代码中我已标出来 


代码不算太复杂,但是有一个参数能帮助我们更快的确定mysql的batch工作机制,那就是 
mysql jdbc driver 的connection url, 其中有一个参数是: rewriteBatchedStatements
 

完整的参数参考看这里:http://ftp.ntu.edu.tw/ftp/pub/MySQL/doc/refman/5.1/en/connector-j-reference-configuration-properties.html

rewriteBatchedStatements 参数默认为false, 需要手工设置为true,设置方式大概像这样:

[java]  view plain  copy
  1. String connectionUrl="jdbc:mysql://192.168.1.100:3306/test?rewriteBatchedStatements=true";      

默认时候,rewriteBatchedStatements=false时,执行路径会跳到 executeBatchSerially,此方法内部将语句一条条发送,与非batch处理简直一样,所以慢,就在这里了。

当设为 true时,会执行executeBatchedInserts方法,事实上mysql支持这样的插入语句

[sql]  view plain  copy
  1. insert into t_user(id,uname) values(1, '1'), (2,'2'), (3, '3') ....    

针对rewriteBatchedStatements=true 参数我做了测试,我加了这个参数,做同们的插入10万条记录测试: 
我的mysql 安装的虚拟机上,所以慢一些。 
MySql JDBC 驱动版本结果
5.0.8没有提高 18秒
5.1.7没有提高 18秒
5.1.13有提高 1.6秒

所以Mysql的批量操作一定要加上MySql连接的url中要加rewriteBatchedStatements参数设为true。


最后贴下代码:

  1. public static void batchSave() {
  2. new Thread() {
  3. public void run() {
  4. long start = System.currentTimeMillis();
  5. Connection conn = null;
  6. PreparedStatement pstmt = null;
  7. try {
  8. String sql = "insert into bluetooth_code_raw(rawCode, md5Code) values(?,?)";
  9. conn = db1.conn;
  10. // JAVA默认为TRUE,我们自己处理需要设置为FALSE,并且修改为手动提交,才可以调用rollback()函数
  11. conn.setAutoCommit(false);
  12. pstmt = conn.prepareStatement(sql);
  13. for (int i = 0; i < 100000; i++) {
  14. String gunCode = MagicCodeUtil.generateGunCode(0, i);
  15. pstmt.setString(1, gunCode);
  16. pstmt.setString(2, MagicCodeUtil.getMd5(gunCode));
  17. pstmt.addBatch();
  18. //防止内存溢出,我也不是很清楚都这么写
  19. if ((i + 1) % 1000 == 0) {
  20. pstmt.executeBatch();
  21. pstmt.clearBatch();
  22. }
  23. }
  24. pstmt.executeBatch(); // 批量执行
  25. conn.commit();// 提交事务
  26. } catch (SQLException e) {
  27. try {
  28. conn.rollback(); // 进行事务回滚
  29. } catch (SQLException ex) {
  30. e.printStackTrace();
  31. }
  32. } finally {
  33. if (pstmt != null)
  34. try {
  35. pstmt.close();
  36. } catch (SQLException e) {
  37. e.printStackTrace();
  38. }
  39. if (conn != null)
  40. try {
  41. conn.close();
  42. } catch (SQLException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. System.out.println((System.currentTimeMillis() - start) / 1000);
  47. };
  48. }.start();
  49. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/二进制舞者/article/detail/61818
推荐阅读
相关标签
  

闽ICP备14008679号