我在整个应用程序中都使用了一个sqlite数据库。因此,为了方便起见,我想将到数据库的连接包装在一个单独的实例中。一开始,我认为我可以保留一个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()来响应用户输入。第二种方法是此设置的最佳选择吗?
谢谢
发布于 2013-02-07 15:23:24
你不需要一遍又一遍地写getwritable数据库,只需要做一个db类public DBCustomer open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; }的构造函数,然后调用db的所有函数,只需解对象和调用object.open函数即可
https://stackoverflow.com/questions/14745310
复制相似问题