Java:使用 PreparedStatement 将多行插入 MySQL [英] Java: Insert multiple rows into MySQL with PreparedStatement

查看:33
本文介绍了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.

另见:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆