【问题标题】:Multiple row insert in SQL Server from Java [duplicate]来自Java的SQL Server中的多行插入[重复]
【发布时间】:2011-03-06 22:41:14
【问题描述】:

我需要从我的 Java 代码向 SQL Server 数据库中插入多行(一次 100 行)。我怎样才能做到这一点?目前我正在一个一个插入,这看起来效率不高。

【问题讨论】:

    标签: java sql sql-server jdbc


    【解决方案1】:

    使用批处理。

    查看Java的Statement的addBatch()、executeBatch()等方法

    举个简单的例子,检查here(但我建议使用 PreparedStatement)

    【讨论】:

    • sql server 中有批处理语句还是需要使用api...?
    • @Kaddy - 我建议在 Java 端使用 PreparedStatement 进行批处理
    【解决方案2】:

    您可以将一个非常长的字符串传递给 SQL,并将多个插入作为一条语句传递给 SQL Server。但是,如果您正在执行参数化查询,这将不起作用。并且串联的 SQL 字符串“通常是个坏主意”。

    查看BULK INSERT 命令可能会更好。它的问题是对列顺序等很严格。但它的方式快!

    【讨论】:

    • 我无法使用它,因为我没有文件...无论如何谢谢...
    • 是的,它是一个 PITA 来写入文件等,但它是一个需要注意的好命令。 :)
    【解决方案3】:

    您可以使用PreparedStatement#addBatch() 创建批处理并使用executeBatch() 执行它。

    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = database.getConnection();
        statement = connection.prepareStatement(SQL);
        for (int i = 0; i < items.size(); i++) {
            Item item = items.get(i);
            statement.setString(1, item.getSomeValue());
            // ...
            statement.addBatch();
            if ((i + 1) % 100 == 0) {
                statement.executeBatch(); // Execute every 100 items.
            }
        }
        statement.executeBatch();
    } finally {
        if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
        if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
    }
    

    另见

    【讨论】:

    • 在这种方法中,如果批处理中的一条记录失败会发生什么..?是否会插入失败记录之后的记录...我如何确保除了失败的记录之外的所有其他记录都被插入...?
    • 这实际上取决于使用的驱动程序。见executeBatch() javadoc
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多