开发者

Managing SQLite Connections in Android

I have a (hopefully) quick question regarding handling SQLite database connections in Android. I have an app that is composed, naturally, of several activities. I have no trouble creating/updating/querying the database, as I've created a single, dedicated class to handle that work via SQLiteOpenHelper, etc.

My question is this: since these activities all share this same database, is this usually implemented as a 开发者_高级运维single, static member, or should each activity own its own connection? My concern of course is the cost of re-connecting to the database in each activity.

Or, put another way, is there any reason not to just store a singleton instance?

I'm also wondering if there's something going on behind the scenes similar to .NET's connection pooling to reduce the cost of opening connections.

Thanks in advance!


Connection opening in SQLite is about 0.2ms.

The best practice tells us to open and close the connection each time we need one.


Just use SQLiteOpenHelper.getReadableDatabase() and SQLiteOpenHelper.getWriteableDatabase() - Android will manage and cache the connection so you don't need to.

In fact, refer to the official Google Using Databases documentation:

To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜