如何让SQLite的连接更加高效 [英] how to make SQLite connections more efficient
问题描述
有什么优势,在保持本地sqlite的连接打开,该活动正在运行的全部时间?
我通常会创建一个新的连接,然后每个执行数据库操作方法内关闭。它看起来是这样的:
myMethod的(上下文的背景下){
LocalDBHelper localDBHelper =新LocalDBHelper(背景); //扩展SQLiteOpenHelper
SQLiteDatabase分贝= localDBHelper.getWritableDatabase();
...
localDBHelper.close();
}
因此,在一个典型的用户会话,这会发生大约10次。难道是有意义的创建 onResume())的连接
,使用,在所有的数据库访问方法,最后关闭它在的onPause(
有什么优势,在保持本地sqlite的连接打开,该活动正在运行的全部时间?
块引用>您通常想为你的流程的整个生命一连接。特别是,你不希望在多个线程同时在使用多个连接。所有的SQLite在Android的线程安全逻辑是基于使用单个
SQLiteDatabase
(,因此,单SQLiteOpenHelper
)所有这些线程,所以适当的锁定可以做到的。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 inonPause()
?解决方案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, singleSQLiteOpenHelper
) for all of those threads, so proper locking can be done.这篇关于如何让SQLite的连接更加高效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!