java - 与顺序执行多个查询相比,使用 addBatch() 和 executeBatch() 有什么优势吗?
问题描述
我遇到了一个场景,我必须将 20 行插入数据库 (SQLite)。我遵循的方法是创建一个update
方法,该方法将采用 aString
和 afloat
并将它们设置在 a 中PreparedStatement
。我曾经调用此更新方法 20 次来插入所有行。这是我的更新方法:
void update(String variableName, int value) throws SQLException {
String query = "INSERT OR REPLACE INTO Table1 (STRINGNAME, VALUE) VALUES(?,?)";
try (Connection connection = getDataSource().getConnection();
PreparedStatement pst = connection.prepareStatement(query);) {
pst.setString(1, variableName);
pst.setInt(2, value);
pst.executeUpdate();
}
}
我知道有一项规定可以批量添加多个查询addBatch
并executeBatch
使用PreparedStatement
.
根据我的理解,addBatch
将向Statement
对象的当前命令列表添加一个 SQL 查询,executeBatch
并将执行列表中的所有查询。这不等同于update
多次调用该方法(除了初始化之外PreparedStatement
)?多次使用addbatch
和executeBatch
过度执行该方法是否有任何性能优势?update
更新
我测试了这两种情况:一种是批量更新,另一种是update
针对 20000 个查询的方法的修改版本。
updateCommon
, 修改后update
的常用方法PreparedStatment
:
void updateCommon(String variableName, int value, PreparedStatement pst) throws SQLException {
pst.setString(1, variableName);
pst.setInt(2, value);
pst.executeUpdate();
}
updateBatch
方法,将数据添加到批处理中:
void updateBatch(String variableName, float value, PreparedStatement pst) throws SQLException {
pst.setString(1, variableName);
pst.setInt(2, value);
pst.addBatch();
}
测试
updateCommon
测试如下:
try {
Connection conn = getDataSource().getConnection();
PreparedStatement pst = conn.prepareStatement(query);
for (int i = 0; i < 1000; i++) {
updateCommon("String1" + i, 1, pst);
/*
* till 20
*/
updateCommon("String20" + i, 20, pst);
}
}
updateBatch
测试如下:
try (Connection conn = getDataSource().getConnection(); PreparedStatement pst = conn.prepareStatement(query); ) {
for (int i = 0; i < 1000; i++) {
updateBatch("String1" + i, 1, pst);
/*
* till 20
*/
updateBatch("String20" + i, 20, pst);
}
pst.executeBatch();
}
结果:
方法完成测试所用时间updateCommon
:117.2 秒方法完成测试
所用时间updateBatch
:267.6 秒
这进一步使这个问题看起来更有趣,PreparedStatement
在这个特定的用例中,使用公共直接更新几乎快两倍。
因此,使用 addBatch() 和 executeBatch() 比顺序执行多个查询有什么优势吗?
解决方案
是的,有性能优势。
调用您的更新方法 20 次将执行 20 个插入语句。
使用 addBatch/executeBatch 方式,只执行一个插入语句,一次插入 20 行,这样更快。
尽管您可能无法识别出 20 行的区别,但您会发现有几个 1000 行。
推荐阅读
- node.js - 在 request-promise-native 中发送带有路径变量的 API GET 请求
- java - 杰克逊反序列化为子元素列表
- unicode - 是否保证 mbcs 编码中的尾随字节在特定范围内?
- php - 如何使用 google drive api 托管或流式传输在 google drive 中上传的视频
- php - 使用谷歌 API 凭证时需要验证码的谷歌页面速度洞察 API
- python - Python中的浮点不准确 - 如何修复
- java - 如何映射到 h2 中的数组数据类型
- go - 如何根据我发送给 Go 函数的变量返回特定类型的切片
- javascript - Chrome 76 使用导航器将内容复制到剪贴板
- json - 用于 Contentful 的 JSON 配置中的意外令牌}