本文介绍了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)?

推荐答案

您可以通过并通过。

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 tutorial - Using PreparedStatement
  • JDBC tutorial - Using Statement Objects for Batch Updates

这篇关于Java:使用PreparedStatement在MySQL中插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 09:35