【问题标题】:SQLite Java Insert - Many smaller inserts versus fewer, larger insertsSQLite Java 插入 - 许多较小的插入与更少、较大的插入
【发布时间】:2018-02-26 16:59:24
【问题描述】:

我有一个数据库线程,每 500 毫秒将所有插入查询排序到一个事务中。目前,该应用程序对每条数据进行一次插入。将这些许多插入语句排序为相似的插入并使用更多元素执行更少的插入会更有效还是效率更低?我正在尝试减少插入所需的 CPU 功率。

IE(但实际上它的规模更大,元素更多)

Start Transaction
INSERT (A,B,C) INTO TABLE VALUES(1,2,3)
INSERT (A,B,C) INTO TABLE VALUES(4,5,6)
INSERT (A,B,C) INTO TABLE VALUES(7,8,9)
INSERT (A,B,C) INTO TABLE VALUES(10,11,12)
INSERT (A,B,C) INTO TABLE VALUES(13,14,15)
INSERT (A,B,C) INTO TABLE2 VALUES(1,2,3)
INSERT (A,B,C) INTO TABLE2 VALUES(4,5,6)
INSERT (A,B,C) INTO TABLE2 VALUES(7,8,9)
INSERT (A,B,C) INTO TABLE2 VALUES(10,11,12)
INSERT (A,B,C) INTO TABLE2 VALUES(13,14,15)
End Transaction

Versus

Start Transaction
INSERT(A,B,C) INTO TABLE VALUES((1,2,3),(4,5,6),(7,8,9),(10,11,12),(13,14,15))
INSERT(A,B,C) INTO TABLE2 VALUES((1,2,3),(4,5,6),(7,8,9),(10,11,12),(13,14,15))
End Transaction

要求的代码:

public void dbCallInsert(List<String> query) {
    // Good practice to create a new statement and result set instead of reusing
    Statement stmt = null;
    Connection conn = null;

    try {
        // Fetch the query and the request out of the QueryRequest object
        conn = cpds.getConnection();
        conn.setAutoCommit(false);
        stmt = conn.createStatement();
        String temp;

        for (String a: query) {                    
            stmt.execute(a);
        }

        conn.commit();
        stmt.close();
        conn.close();

    } catch (Exception e) {

        errorLog.error("Failed to issue database command " + query + ": " + e);

    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                errorLog.error("Failed to close JDBC statement.");
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                errorLog.error("Failed to close JDBC connection.");
            }
        }
    }
}

【问题讨论】:

  • 我们可以看到您用于插入的 java 代码吗?您使用的是Statement(或PreparedStatement)吗?
  • 按要求添加了代码。使用语句。

标签: java database sqlite


【解决方案1】:

从这个答案中借用Is it possible to insert multiple rows at a time in an SQLite database?

由于您的两个 INSERT 块都包装在 TRANSACTION 中,因此几乎没有区别。见this comment from the SQLite Mailing List:

2012 年 2 月 23 日星期四上午 8:25,Petite Abeille 写道:

2012 年 2 月 23 日下午 2:16,Abhinav Upadhyay 写道:

。我想知道是否可以使用 单个 INSERT 查询

啊,另外,使用复合插入并没有太大的好处。

您也可以简单地将所有值插入到一笔交易中,然后 完成。

另一方面,即将发布的 3.7.11 版本似乎支持 多值插入语句。

http://www.sqlite.org/draft/releaselog/3_7_11.html

新的多值插入只是复合词的语法糖 插入。无论哪种方式都没有性能优势。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2018-05-17
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多