What is the best practice when closing SQLiteDatabase in Android?

In official docs, you read:

public SQLiteDatabase getWritableDatabase ()

...

Once opened successfully, the database is cached, so you can call this method every time you need to write to the database. (Make sure to call close() when you no longer need the database.)

As for the SQLiteOpenHelper, I implemented a singleton pattern for the only instance, but how about the SQLiteDatabase?
How effective is the cache?

Android SQLite DB When to Close I looked at this post, but there is no discussion over caching.


Open and close your db before and after each operation, respectively.
Never leave it open, when not needed.

Your mantra should be: open it, use it, close it.
Repeat for every db operation.

Same goes for Cursors as well.


I always close my SQLiteDatabase after every query. For example, here's how I implement my insert methods:

public void insert(ContentValues valuesMap){
    SQLiteDatabase db = getWriteableDatabase();
    try{
       db.insert("ContactsTable", null, valuesMap);
    }catch(Exception e){
       // do someting...
    }finally{
       db.close()
    }
}
链接地址: http://www.djcxy.com/p/42628.html

上一篇: 如何设置路径变量

下一篇: 在Android中关闭SQLiteDatabase时的最佳做法是什么?