Reputation: 6742
I'm building a mobile app and I use SQLite as the data-storage...
And I have two approaches for executing sql-query in my mobile-app
First Open a connection to the DB when the app-loads and use it for the lifetime of the app, and close it on-app-close.
Second Open a connection per each-query-execution.
What's better in terms of speed and reliability
Upvotes: 0
Views: 254
Reputation: 898
Besides the recommendation to use Room
, I recommend to use the SQLiteOpenHelper. It is a perfect implementation on how to deal with this question. It opens the DB once and uses this instance over the livetime. The helper even recognizes when the instance got closed and reopens it for you:
Have a single instance of the SQL Helper and make this available to all ViewModels (or controllers or whatsoever).
For example you could have a static reference in your MainApp (if you use multiple activities) or in your MainActivity (if you only use one) and then just access it by MainActivity.getDbHelper()
.
Where you need access you can then call
db = dbHelper.getReadableDatabase()
// or
db = dbHelper.getWriteableDatabase()
and get your cursor by a query() or modify the db with exec()
Update:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "dbName.db";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_YOUR_TABLE_STRING);
}
}
Upvotes: 1