SQLiteOpenHelper multiple databases in memory

android.database.sqlite.SQLiteOpenHelper provides the ability to use the database in memory if the name argument to its constructor is null :

String: database file or null for in-memory database

If SQLiteOpenHelper is created multiple times with the null name argument, do they access the same database in memory or are they a separate memory database created each time?

+5
source share
2 answers

From the official documentation of SQLite Databases with memory

Opening two database connections with the file name: ": memory:" will create two independent databases in memory.

On Android, pass null instead of ": memory:"

So, if you create an instance of SQLiteOpenHelper several times with a null-name argument, it creates each separate database in memory created each time

+4
source

If we look at the source code , we will see that the constructor mName will be set to null .

 public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version, DatabaseErrorHandler errorHandler) { if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version); mContext = context; mName = name; mFactory = factory; mNewVersion = version; mErrorHandler = errorHandler; } 

This means that getDatabaseName() returns null .

 public String getDatabaseName() { return mName; } 

Later, using getReadableDatabase() or getWritableDatabase() , if mName is null , it calls the create method for the database in memory instead of trying to open it from disk.

 if (mName == null) { db = SQLiteDatabase.create(null); // in-memory } else { // db file opened or created } ... return db; 

This db variable is maintained in SQLiteOpenHelper until it is closed, which in the case of a database in memory means that the data has been deleted.


To clarify,

Each instance of SQLiteOpenHelper that uses the database in memory will be its own database, while the same instance will use the same database and keep this data until it is closed.

+3
source

All Articles