使用JDBC在MySQL数据库中如何快速批量插入数据
作者:PlusPlus1 发布时间:2024-01-18 04:04:13
使用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()。
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 = null;
while (null != (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语句。
useServerPrepStmts=false,如果不开启(useServerPrepStmts=false),使用com.mysql.jdbc.PreparedStatement进行本地SQL拼装,最后送到db上就是已经替换了?后的最终SQL.
在此稍加改进,连接字符串中加入下面语句(代码构造方法中去掉注释):
connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true";
再次执行如下:
All down : 103498
Convert finished.
All spend time/s : 10
同样的数据量,这次执行只花费了10秒 ,处理效率大大提高.
猜你喜欢
- 开始安装Androidstudio 4.1克隆此项目git clone https://github.com/pytorch/android
- 说明1、如果数据集是高维度的,选择谱聚类是子空间的一种。2、如果数据量是中小型的,比如在100W条以内,K均值会是更好的选择;如果数据量超过
- Python中的魔法方法方法名说明__str__用于返回对象的描述__iter__使类可以迭代__getitem__按照下标获取类元素,例如
- 集合(set)是一个无序的不重复元素序列。可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而
- 在上一篇文章中 ,我说到:强硬的把CSS和HTML塞到PHP里面可以防止代码太枯燥(DRY)并最终导致代码臃肿,因为的CSS和HTML需要比
- 装饰器(decorator)是一种高级Python语法。装饰器可以对一个函数、方法或者类进行加工。在Python中,我们有多种方法对函数和类
- 本博文源于python科学计算,旨在解析如何使用python进行计算分段函数值。下面就以复杂的二元函数进行演示。题目再现求解思路首先先生成x
- 游戏说明:一个考验您记忆力的游戏,只要两个方块的;图案能够凑成一对,最终翻开所有的图片,那么您就获胜,计算机将自动记录您的游戏时
- 目录1. 最直观的相加2. 借助 itertools3. 使用 * 解包4. 使用 extend5. 使用列表推导式6. 使用 heapq7
- F查询在上面所有的例子中,我们构造的过滤器都只是将字段值与某个我们自己设定的常量做比较。如果我们要对两个字段的值做比较,那该怎么做呢?Dja
- 首先介紹一下我們用360搜索派取城市排名前20。我们爬取的网址:https://baike.so.com/doc/24368318-2518
- 经常会看到这种弹出层背景变暗的效果,感觉手痒于是自己写了一个基于jquery的弹出层类。我习惯先写好结构和样式,然后再写js交互效果。结构定
- mysql5.5.28安装教程,供大家参考,具体内容如下安装步骤:1、首先单击mysql-5.5.28的安装文件,出现该数据库的安装向导界面
- 1.Django实现WebSocket在线聊天室1.1 安装pip install channels==2.3(saas) F:\Deskt
- 什么是转义字符在 HTML 中 <、>、& 等字符有特殊含义(<,> 用于标签中,& 用于转义),他
- 前言:今天要介绍这个神器,可以说是 pywebio 的 Plus + Pro&nbs
- 前言值类型:所有像int、float、bool和string这些类型都属于值类型,使用这些类型的变量直接指向存在内存中的值,值类型的变量的值
- 良好的编程习惯是每个程序员都应该具备的工作素质,在我的软件生涯中屡屡发现一些程序员的身上总有这样或者那样的坏毛病。这些毛病在一些从业时间不是
- 这篇文章主要介绍了python中如何使用insert函数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 从wind上面搞到一批股票数据后发现:本来是一个类型的数据,但是由于季度不同,列名也不同,导致使用pandas合并多个报表的时候总是出现一大