java - 在单个 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)的方法是一种好方法,还是有更好的方法呢?
更新:
根据一些测试,与批量更新相比,这种在单个查询中更新的方式非常快(请参阅此问题中的更新)。唯一的问题是,这种在单个查询中更新的方式是否有任何缺陷,或者是否有更好的方法来实现这一点?
解决方案
要么在循环内运行 executeUpdate,要么更好地批量添加它们并运行整个批处理:pst.addBatch()
在循环中和pst.executeBatch()
循环之后
推荐阅读
- flutter - 应用再次启动时如何使用共享偏好打开特定屏幕
- json - DRF:发出外部请求并构建序列化程序
- node.js - 如何在 Op 中分配 Sequelize 的比较运算符
- javascript - 如何处理 Caesars Cipher (Javascript) 中的负偏移
- c# - ASP.NET Core Razor 页面 - 不绑定 POST 请求
- spotify - 我可以用位置索引替换播放列表中的歌曲吗
- r - 使用 Dplyr 将每行中一列右侧的所有单元格相加
- java - 我如何使用流实现与 Java 8 相同的功能
- vue.js - 添加一个v-date-picker,一个个性化的下拉列表(v-select)vuetify
- c# - return Partial() throws 传入字典的模型项的类型是 .. 但是这个字典需要一个错误类型的模型项