如何让SQLite的连接更加高效高效、SQLite

2023-09-07 09:50:26 作者:夜夜承欢

有什么优势,在保持本地sqlite的连接打开,该活动正在运行的全部时间?

我通常会创建一个新的连接,然后每个执行数据库操作方法内关闭。它看起来是这样的:

  myMethod的(上下文的背景下){    LocalDBHelper localDBHelper =新LocalDBHelper(背景); //扩展SQLiteOpenHelper    SQLiteDatabase分贝= localDBHelper.getWritableDatabase();    ...    localDBHelper.close();} 

因此​​,在一个典型的用户会话,这会发生大约10次。难道是有意义的创建 onResume())的连接,使用,在所有的数据库访问方法,最后关闭它在的onPause(

解决方案   

有什么优势,在保持本地sqlite的连接打开,该活动正在运行的全部时间?

您通常想为你的流程的整个生命一连接。特别是,你不希望在多个线程同时在使用多个连接。所有的SQLite在Android的线程安全逻辑是基于使用单个 SQLiteDatabase (,因此,单 SQLiteOpenHelper )所有这些线程,所以适当的锁定可以做到的。

SQLite之C 连接SQLite

Is there any advantage in keeping a local sqlite connection open the entire time that the activity is running?

I usually create a new connection and then close it within every method that does a database operation. It would look something like this :

myMethod(Context context){
    LocalDBHelper localDBHelper = new LocalDBHelper(context); //extended SQLiteOpenHelper 
    SQLiteDatabase db = localDBHelper.getWritableDatabase();
    ...
    localDBHelper.close();
}

So in a typical user session, this would happen around 10 times. Would it make sense to create a connection in onResume(), use that in all the database access methods and finally close it in onPause()?

解决方案

Is there any advantage in keeping a local sqlite connection open the entire time that the activity is running?

You usually want one "connection" for the entire life of your process. In particular, you do not want to have multiple "connections" in use simultaneously across multiple threads. All of the thread-safety logic for SQLite in Android is based around using a single SQLiteDatabase (and, hence, single SQLiteOpenHelper) for all of those threads, so proper locking can be done.