When to close db connection on android? Every time after your operation finished or after your app exit When to close db connection on android? Every time after your operation finished or after your app exit sqlite sqlite

When to close db connection on android? Every time after your operation finished or after your app exit


I don't know of any performance penalties in frequent closing/opening of the database (regardless of its size). I think the answer to this question also depends on what type of application is accessing the database.

Do you "re-query" the database a lot?
Then it seems rectified to keep it open.

Do you fetch different data each time you fetch something?
Again, it seems reasonable to leave it open (as you won't gain in caching the data instead).

Are there any other applications accessing the same database?
If there is a risk for concurrency or blocking issues, it might be wise to close the database after finished reading/writing from/to it.

Generally I would say that you might gain more in caching data than in leaving the database open (contra closing it) when optimizing for performance.


If you are using an in memory database then your data will be discarded when you close the connection.

A bit of an edge case perhaps, but it just caught me out.


The documentation says the connection can be open as long as you need it. And can be closed in onDestroy() method. Documentation link

Persisting Database Connection:

Since getWritableDatabase() and getReadableDatabase() are expensive to call when the database is closed, you should leave your database connection open for as long as you possibly need to access it. Typically, it is optimal to close the database in the onDestroy() of the calling Activity.

    @Override    protected void onDestroy() {        mDbHelper.close();        super.onDestroy();    }