首页 > 解决方案 > 与顺序执行多个查询相比,使用 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();
    }
}

我知道有一项规定可以批量添加多个查询addBatchexecuteBatch使用PreparedStatement.

根据我的理解,addBatch将向Statement对象的当前命令列表添加一个 SQL 查询,executeBatch并将执行列表中的所有查询。这不等同于update多次调用该方法(除了初始化之外PreparedStatement)?多次使用addbatchexecuteBatch过度执行该方法是否有任何性能优势?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() 比顺序执行多个查询有什么优势吗?

标签: javasqlite

解决方案


是的,有性能优势。
调用您的更新方法 20 次将执行 20 个插入语句。

使用 addBatch/executeBatch 方式,只执行一个插入语句,一次插入 20 行,这样更快。

尽管您可能无法识别出 20 行的区别,但您会发现有几个 1000 行。


推荐阅读