1
我在整個應用程序中使用單個sqlite數據庫。所以我想爲了方便而在一個單例中包裝一個到db的連接。起初,我以爲我可以保持到SQLiteDatabase參考周圍爲:保持對SQLiteDatabase的全局引用?
MySQLiteOpenHelper helper = new MySQLiteOpenHelper(appContext); // local
myGlobalSQLiteDatabase = helper.getWritableDatabase(); // global
...
void someFunction() {
try {
myGlobalSQLiteDatabase.insertOrThrow(...);
} catch (Exception ex) {
}
}
但是這會導致錯誤,如:
(1802) os_unix.c:30011: (2) stat(/data/data/com.me.test/databases/test.db) -
(1802) statement aborts at 16: [INSERT INTO mytable(f1,f2) VALUES (?,?)]
android.database.sqlite.SQLiteDiskIOException: disk I/O error (code 1802)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
...
(這是所有被主線程上完成,單一測試)。
我的第二次嘗試,而不是保持全球僅參考幫手:
myGlobalSQLiteOpenHelper helper = new MySQLiteOpenHelper(appContext); // global
...
void someFunction() {
SQLiteDatabase db = myGlobalSQLiteOpenHelper.getWritableDatabase();
try {
db.insertOrThrow(...);
} catch (Exception ex) {
} finally {
db.close();
}
}
和工程。我必須在每次調用someFunction()時調用getWritableDatabase()和close()。
我不知道getWritableDatabase()和close()中有多少開銷,我最初希望儘可能快的實現,因爲我將重複調用someFunction()以響應用戶輸入。第二種方法是該設置的最佳選擇嗎?
感謝