首页 > 解决方案 > 在单个 SQL 查询中使用 PreparedStatment 在循环中使用 setter 进行多次插入

问题描述

我有一个场景,我应该对数据库进行 20 次插入。我遇到了这个问题,其回答指出在单个查询中进行多次插入比在多个查询中进行一次插入更好。为了适应这一点,我做了以下事情:

HashMap<String, Integer> values = new HashMap<>();
values.put("String1", 1);
/**
* add other values
*/
values.put("String20", 20);

update(values);

而我的更新方法:

private void update(HashMap<String, Integer> map) throws SQLException {

    StringBuilder queryBuilder = new StringBuilder(
            "INSERT OR REPLACE INTO Table1 (STRINGNAME, VALUE) VALUES ");
    for (int i = 0; i < map.size() - 1; i++) {
        queryBuilder.append("(?,?), ");
    }
    queryBuilder.append("(?,?);");
    try (Connection connection = getDataSource().getConnection();
            PreparedStatement pst = connection.prepareStatement(queryBuilder.toString());) {
        int i = 1;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            pst.setString(i++, entry.getKey());
            pst.setInt(i++, entry.getValue());
        }
        pst.executeUpdate();
    }
}

我已经看到了这个问题及其答案。但是没有一个答案在单个查询中有多个插入,而是有批量更新或循环更新。

这是我能想到的在单个查询中进行多次插入的唯一方法。这种使用单个查询将多个元组插入数据库(SQLite)的方法是一种好方法,还是有更好的方法呢?

更新:

根据一些测试,与批量更新相比,这种在单个查询中更新的方式非常快(请参阅此问题中的更新)。唯一的问题是,这种在单个查询中更新的方式是否有任何缺陷,或者是否有更好的方法来实现这一点?

标签: javasqlite

解决方案


要么在循环内运行 executeUpdate,要么更好地批量添加它们并运行整个批处理:pst.addBatch()在循环中和pst.executeBatch()循环之后


推荐阅读