您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Java:使用PreparedStatement将多行插入MySQL

Java:使用PreparedStatement将多行插入MySQL

你可以通过创建批处理PreparedStatement#addBatch()并通过执行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.
            }
        }
    }
}

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

MySQL 2022/1/1 18:18:08 有509人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶