使用JDBC在MySQL数据库中快速批量插入数据

使用JDBC连接MySQL数据库进行数据插入的时候,特别是大批量数据连续插入(10W+),如何提高效率呢?

在JDBC编程接口中Statement 有两个方法特别值得注意:
Adds a set of parameters to this PreparedStatement object's batch of commands.

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()。

package cyl.demo.ipsearcher;  
  
import java.io.BufferedReader;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.SQLException;  
  
public class DbStoreHelper {  
  
    private String insert_sql;  
    private String charset;  
    private boolean debug;  
  
    private String connectStr;  
    private String username;  
    private String password;  
  
    public DbStoreHelper() {  
        connectStr = "jdbc:mysql://localhost:3306/db_ip";  
        // connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true";  
        insert_sql = "INSERT INTO tb_ipinfos (iplong1,iplong2,ipstr1,ipstr2,ipdesc) VALUES (?,?,?,?,?)";  
        charset = "gbk";  
        debug = true;  
        username = "root";  
        password = "***";  
    }  
  
    public void storeToDb(String srcFile) throws IOException {  
        BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), charset));  
        try {  
            doStore(bfr);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            bfr.close();  
        }  
    }  
  
    private void doStore(BufferedReader bfr) throws ClassNotFoundException, SQLException, IOException {  
        Class.forName("com.mysql.jdbc.Driver");  
        Connection conn = DriverManager.getConnection(connectStr, username,password);  
        conn.setAutoCommit(false); // 设置手动提交  
        int count = 0;  
        PreparedStatement psts = conn.prepareStatement(insert_sql);  
        String line = ;  
        while ( != (line = bfr.readLine())) {  
            String[] infos = line.split(";");  
            if (infos.length < 5)   continue;  
            if (debug) {  
                System.out.println(line);  
            }  
            psts.setLong(1, Long.valueOf(infos[0]));  
            psts.setLong(2, Long.valueOf(infos[1]));  
            psts.setString(3, infos[2]);  
            psts.setString(4, infos[3]);  
            psts.setString(5, infos[4]);  
            psts.addBatch();          // 加入批量处理  
            count++;              
        }  
        psts.executeBatch(); // 执行批量处理  
        conn.commit();  // 提交  
        System.out.println("All down : " + count);  
        conn.close();  
    }  
  
}  

执行完成以后:

All down : 103498  
Convert finished.  
All spend time/s : 47 

一共10W+,执行时间一共花费 47 秒.

这个效率仍然不高,似乎没有达到想要的效果,需要进一步改进。
在MySQL JDBC连接字符串中还可以加入参数,
rewriteBatchedStatements=true,mysql默认关闭了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"; 
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 6,479评论 0赞 4
  • 本人的环境为Myeclipse10、MySQL5.7.15 本文包括:简介JDBC编程步骤打通数据库程序详解—Dr...
    廖少少阅读 4,396评论 7赞 39
  • JDBC概述 在Java中,数据库存取技术可分为如下几类:JDBC直接访问数据库、JDO技术、第三方O/R工具,如...
    usopp阅读 3,688评论 3赞 75
  • “那些年,我们一起追过的剧”,这个话题的开始呢,是由于一个舍友在看《七月与安生》而引起的,她看完影片之后,一直在跟...
    天空之城的猫咪阅读 290评论 0赞 0
  • 佛说前世五百次回眸才换来今生一次插肩而过,对于除去211,985,等多所名校聚在一起的室友,到底是缘分,还是我的...
    寸心悟阅读 660评论 2赞 6

友情链接更多精彩内容