位置: 编程技术 - 正文

使用JDBC在MySQL数据库中如何快速批量插入数据(mysql jdbc)

编辑:rootadmin

推荐整理分享使用JDBC在MySQL数据库中如何快速批量插入数据(mysql jdbc),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:mysql-jdbc,jdbc添加数据到mysql,jdbc操作mysql,jdbc添加数据到mysql,使用jdbc操作数据库步骤,jdbc mysql8,mysql-jdbc,jdbc操作mysql数据库,内容如对您有帮助,希望把文章链接给更多的朋友!

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

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

执行完成以后:

使用JDBC在MySQL数据库中如何快速批量插入数据(mysql jdbc)

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

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

这个效率仍然不高,似乎没有达到想要的效果,需要进一步改进。

在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 : Convert finished. All spend time/s :

同样的数据量,这次执行只花费了秒 ,处理效率大大提高.

本文链接地址:https://www.jiuchutong.com/biancheng/349236.html 转载请保留说明!

上一篇:Mysql Explain 详细介绍

下一篇:CentOS中mysql cluster安装部署教程

免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络