使用JDBC在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()。
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  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. }  

执行完成以后:
[plain]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  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";

再次执行如下:
[plain]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. All down : 103498  
  2. Convert finished.  
  3. All spend time/s : 10  
同样的数据量,这次执行只花费了10秒 ,处理效率大大提高.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值