Lorenzo Benevento
Lorenzo Benevento

Reputation: 618

Accessing old Room database in Room Migrations

I have updated my database structure and I moved the data contained in one DB (let's call it DB 1) into a table of another DB (let's call it DB 2).

How do I get an instance of the old DB (DB 1) in room migration to move data from DB 1 to the new table created in DB 2?

Thank you everyone.

Upvotes: 1

Views: 332

Answers (1)

MikeT
MikeT

Reputation: 56943

You have two options assuming that both databases are on the device:-

You can open it as an SQLiteDatabase using the [openDatabase][1] method, obviously closing it when done.

  • This method doesn't allow direct copying/moving via SQL you would extract into a Cursor and then load from the Cursor.

Alternately you can ATTACH the old to the new ensuring that you DETACH after the data has been moved. Noting that use of the schema name can be crucial when accessing the old db (attached).

  • This does facilitate direct copying using SQL.
  • note that DATABASE is the path to the database AND that it should be enclosed in single quotes. e.g. main_sdb.execSQL("ATTACH DATABASE '" + other_sdb.getPath() + "' AS other"); main_sdb being a SupportSQliteDatabase instance (as passed to the Migration) in this case the path of the database being attached is retrieved from another such instance. The schema name is other

Upvotes: 3

Related Questions