Java:使用 PreparedStatement 将多行插入 MySQL

编程入门 行业动态 更新时间:2024-10-28 18:22:30
本文介绍了Java:使用 PreparedStatement 将多行插入 MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用 Java 一次将多行插入到 MySQL 表中.行数是动态的.过去我在做...

I want to insert multiple rows into a MySQL table at once using Java. The number of rows is dynamic. In the past I was doing...

for (String element : array) { myStatement.setString(1, element[0]); myStatement.setString(2, element[1]); myStatement.executeUpdate(); }

我想优化它以使用 MySQL 支持的语法:

I'd like to optimize this to use the MySQL-supported syntax:

INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]

但是使用 PreparedStatement 我不知道有什么方法可以做到这一点,因为我事先不知道 array 将包含多少个元素.如果使用 PreparedStatement 无法实现,我还能怎么做(并且仍然转义数组中的值)?

but with a PreparedStatement I don't know of any way to do this since I don't know beforehand how many elements array will contain. If it's not possible with a PreparedStatement, how else can I do it (and still escape the values in the array)?

推荐答案

您可以通过 PreparedStatement#addBatch() 并通过PreparedStatement#executeBatch().

You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch().

这是一个启动示例:

public void save(List<Entity> entities) throws SQLException { try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_INSERT); ) { int i = 0; for (Entity entity : entities) { statement.setString(1, entity.getSomeProperty()); // ... statement.addBatch(); i++; if (i % 1000 == 0 || i == entities.size()) { statement.executeBatch(); // Execute every 1000 items. } } } }

它每 1000 个项目执行一次,因为某些 JDBC 驱动程序和/或数据库可能对批处理长度有限制.

It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.

另见:

  • JDBC 教程 - 使用 PreparedStatement
  • JDBC 教程 - 使用语句对象进行批量更新

更多推荐

Java:使用 PreparedStatement 将多行插入 MySQL

本文发布于:2023-11-27 18:33:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639131.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:PreparedStatement   Java   MySQL   将多行

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!