我有大約7000行想要插入到設備的(Android galaxy tab2)sqlite數據庫。目前,我正在解析JSON文件並使用「for」循環將行插入到數據庫中。但它需要超過120秒才能解析和插入數據到sqlite數據庫中。有沒有其他更快的方法來做到這一點?什麼是在sqlite數據庫中插入行的最快方式
謝謝...
我有大約7000行想要插入到設備的(Android galaxy tab2)sqlite數據庫。目前,我正在解析JSON文件並使用「for」循環將行插入到數據庫中。但它需要超過120秒才能解析和插入數據到sqlite數據庫中。有沒有其他更快的方法來做到這一點?什麼是在sqlite數據庫中插入行的最快方式
謝謝...
我遇到了完全相同的情況。首先我使用的是DatabaseUtil.insertHelper,它爲我帶來了+30秒的600個參賽作品。
我做了更多的挖掘,發現我插入的每一行都被提交,這是非常昂貴的。
爲了解決這個問題,我切換到ORMLite,與insertAll方法:
/**
* Inserts multiple objects into the database quickly by committing them all at once
*
* @param objects The objects to insert
*/
public void insertAll(final T[] objects) {
try {
dao.callBatchTasks(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (T object : objects) {
dao.create(object);
}
return null;
}
});
} catch (Exception e) {
AdbLogger.error("Error inserting new " + className + "s in the database");
}
}
這裏的想法是,他們這樣做對象的數組的插入,然後在最後只能做一個大的承諾。在這個開關後插入變得幾乎是瞬間的。
@ wangyyif2:非常感謝,我會試試這個。希望它能工作:-) – RHL
您應該使用statements
database.beginTransaction();
SQLiteStatement stmt = database.compileStatement(sql);
for (int i = 0; i < NUMBER_OF_ROWS; i++) {
//generate some values
stmt.bindString(1, randomName);
stmt.bindString(2, randomDescription);
stmt.bindDouble(3, randomPrice);
stmt.bindLong(4, randomNumber);
long entryID = stmt.executeInsert();
stmt.clearBindings();
}
database.setTransactionSuccessful();
database.endTransaction();
Reference
這裏是one more link其中這兩種插入方法之間的比較中給出。 (對於100條記錄,正常插入需要1657ms,而帶有endTransaction()
的語句需要92ms)
使用數據庫事務。 –
你可以用一個查詢插入所有數據嗎?或按批次處理,如每批500個? – dongshengcn
另一個想法是預先插入到sqlite數據,並將數據庫文件託管在某處,然後下載該文件並直接打開它。這是相當戲劇性的變化。 – dongshengcn