簡體   English   中英

如何在Android應用程序中加速數據庫(SQLite)中的大數據插入

[英]How to speed up large data insertion in Database (SQLite) in Android application

我有一種情況,我必須在數據庫中插入數據,並且數據非常大,在ArrayList 數據插入一個循環,如下所示:

for( ..... )
ContentValues cv = new ContentValues();

// cv.put statements

sqLiteDB.insert ......

現在測試用例大約需要1分鍾以上,實際數據預計超過10分鍾,而目標是將時間保持在30秒以下。 數據無法減少。 我的問題是:

  1. 如何提高速度
  2. 有沒有辦法避免重復調用sqLiteDB.insert函數並在一個批處理中插入所有行?

在你的情況下,可能的速度改進之一是有這樣的代碼:

ContentValues cv = new ContentValues();
for(....) {
    //cv put
    sqLiteDB.insert
    cv.clear();
}

此外, 這里有一篇博文如何提高插入速度。

編輯我也檢查了SO, 是一個類似的問題。 它聲稱使用交易可以提高速度。

我沒有為sqlite嘗試這個,但在mssql中做了類似的事情。 大多數情況下打開/關閉事務比插入需要更多時間。 所以你可以在一次交易中做所有事情..值得嘗試。

db.beginTransaction();
try {
    SQLiteStatement insert = null;
    insert = db.compileStatement("INSERT OR REPLACE INTO \"MyTable\" ("
            + "\"MyColumnName\") VALUES (?)");

    for (i = 0; i++; i < 10000)
    {
        insert.bindLong(1, i);
        insert.execute();
        insert.clearBindings();
    }

    db.setTransactionSuccessful();
}
catch (Exception e) {
    String errMsg = (e.getMessage() == null) ? "bulkInsert failed" : e.getMessage();
    Log.e("bulkInsert:", errMsg);
}
finally {
    db.endTransaction();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM