Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to lose a SQLite database connection?

I am seeing few "java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed." exceptions from an Android app. I didn't close the connection in many places. It is also possible that the connection is getting closed in some other thread.

Just to make sure, is it possible for an SQLite connection to get closed automatically or by the operating system or implicitly?

like image 811
brainless Avatar asked Dec 08 '15 16:12

brainless


2 Answers

This source recommends you to use a singleton DatabaseHelper, and some do not demonify it.

This would indicate to me that the Database is not expected to simply close itself during the lifetime of your Application.

First Source @Alex Lockwood

Approach #1: Use a Singleton to Instantiate the SQLiteOpenHelper

Declare your database helper as a static instance variable and use the Singleton pattern to guarantee the singleton property. The sample code below should give you a good idea on how to go about designing the DatabaseHelper class correctly.

The static getInstance() method ensures that only one DatabaseHelper will ever exist at any given time. If the sInstance object has not been initialized, one will be created. If one has already been created then it will simply be returned. You should not initialize your helper object using with new DatabaseHelper(context)! Instead, always use DatabaseHelper.getInstance(context), as it guarantees that only one database helper will exist across the entire application's lifecycle.

Second Source @CommonsWare

Having a single SQLiteOpenHelper instance can help in threading cases. Since all threads would share the common SQLiteDatabase, synchronization of operations is provided.

like image 159
Knossos Avatar answered Oct 01 '22 20:10

Knossos


Yes - any database connection can be closed behind your back. It can happen on the server end if a dba decides to kill your connection. It can happen in the client if something times out. It can happen inside jdbc for various reasons. It can even happen by accident in your code.

There is some ambiguity here though. You report a Cannot perform this operation because the connection pool has been closed. Your connection pool is unlikely to be closed without your knowledge. Also if you use a connection pool correctly it will reopen the database connection if it closes.

like image 22
OldCurmudgeon Avatar answered Oct 01 '22 22:10

OldCurmudgeon