当前位置:网站首页>MySQL数据库10秒内插入百万条数据的实现
MySQL数据库10秒内插入百万条数据的实现
2022-04-23 11:02:00 【liming89】
文章来源: 学习通http://www.bdgxy.com/
首先我们思考一个问题:
要插入如此庞大的数据到数据库,正常情况一定会频繁地进行访问,什么样的机器设备都吃不消。那么如何避免频繁访问数据库,能否做到一次访问,再执行呢?
Java其实已经给了我们答案。
这里就要用到两个关键对象:Statement
、PrepareStatement
我们来看一下二者的特性:
要用到的BaseDao工具类 (jar包 / Maven依赖) (Maven依赖代码附在文末)(封装以便于使用)
注:(重点)rewriteBatchedStatements=true,一次插入多条数据,只插入一次!!
public class BaseDao { // 静态工具类,用于创建数据库连接对象和释放资源,方便调用 // 导入驱动jar包或添加Maven依赖(这里使用的是Maven,Maven依赖代码附在文末) static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
// 获取数据库连接对象 public static Connection getConn() { Connection conn = null; try { // rewriteBatchedStatements=true,一次插入多条数据,只插入一次 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/million-test?rewriteBatchedStatements=true", "root", "qwerdf"); } catch (SQLException throwables) { throwables.printStackTrace(); } return conn; } // 释放资源 public static void closeAll(AutoCloseable... autoCloseables) { for (AutoCloseable autoCloseable : autoCloseables) { if (autoCloseable != null) { try { autoCloseable.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
}
接下来上关键代码及注释:
/* 因为数据库的处理速度是非常惊人的 单次吞吐量很大 执行效率极高
addBatch()把若干sql语句装载到一起,然后一次送到数据库执行,执行需要很短的时间
而preparedStatement.executeUpdate() 是一条一条发往数据库执行的 时间都消耗在数据库连接的传输上面*/
public static void main(String[] args) {
long start = System.currentTimeMillis(); // 获取系统当前时间,方法开始执行前记录
Connection conn = BaseDao.getConn(); // 调用刚刚写好的用于获取连接数据库对象的静态工具类
String sql = "insert into mymilliontest values(null,?,?,?,NOW())"; // 要执行的sql语句
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql); // 获取PreparedStatement对象
// 不断产生sql
for (int i = 0; i < 1000000; i++) {
ps.setString(1, Math.ceil(Math.random() * 1000000) + "");
ps.setString(2, Math.ceil(Math.random() * 1000000) + "");
ps.setString(3, UUID.randomUUID().toString()); // UUID该类用于随机生成一串不会重复的字符串
ps.addBatch(); // 将一组参数添加到此 PreparedStatement 对象的批处理命令中。
}
int[] ints = ps.executeBatch();// 将一批命令提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组。
// 如果数组长度不为0,则说明sql语句成功执行,即百万条数据添加成功!
if (ints.length > 0) {
System.out.println("已成功添加一百万条数据!!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.closeAll(conn, ps); // 调用刚刚写好的静态工具类释放资源
}
long end = System.currentTimeMillis(); // 再次获取系统时间
System.out.println("所用时长:" + (end - start) / 1000 + "秒"); // 两个时间相减即为方法执行所用时长
}
最后我们运行看一下效果:
嘿嘿,这里时长超过了10秒,设备差点意思,希望理解哈~
<!--连接数据库所用到的mysql-connector-java依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency>
PS : 添上线程后会更快,在后续的文章中会作示例。
到此这篇关于MySQL数据库10秒内插入百万条数据的实现的文章就介绍到这了,更多相关MySQL 插入百万条数据 内容请搜索菜鸟教程www.piaodoo.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持菜鸟教程www.piaodoo.com!
版权声明
本文为[liming89]所创,转载请带上原文链接,感谢
https://blog.csdn.net/liming89/article/details/124343110
边栏推荐
- Google Earth engine (GEE) - scale up the original image (taking Hainan as an example)
- Let the LAN group use the remote device
- 精彩回顾|「源」来如此 第六期 - 开源经济与产业投资
- Visual common drawing (III) area map
- CUMCM 2021-b: preparation of C4 olefins by ethanol coupling (2)
- Using El popconfirm and El backtop does not take effect
- Which company is good for opening futures accounts? Who can recommend several safe and reliable futures companies?
- web三大组件(Servlet,Filter,Listener)
- MBA - day5 mathématiques - Questions d'application - Questions d'ingénierie
- SVN的使用:
猜你喜欢
随机推荐
VIM usage
Alarm scene recognition
Derivation and regularization
CUMCM 2021-B:乙醇偶合制備C4烯烴(2)
学习 Go 语言 0x05:《Go 语言之旅》中映射(map)的练习题代码
Using El popconfirm and El backtop does not take effect
Strongest date regular expression
Visual common drawing (IV) histogram
学习网站资料
Read integrity monitoring techniques for vision navigation systems
MySQL8.0升级的踩坑历险记
CUMCM 2021-b: preparation of C4 olefins by ethanol coupling (2)
防止web项目中的SQL注入
The songbird document editor will be open source: starting with but not limited to markdown
MIT:用无监督为世界上每个像素都打上标签!人类:再也不用为1小时视频花800个小时了
How to Ping Baidu development board
Differences among restful, soap, RPC, SOA and microservices
Cumcm 2021 - B: préparation d'oléfines C4 par couplage éthanol (2)
Mba-day6 logic - hypothetical reasoning exercises
Common parameters of ffmpeg command line