Change Live App database without data loss

I want to update the database of my existing app (for the new version) which is live on the app store. Therefore, before using the application, I need to delete the existing database, or I can change the name of the database. After that If the data exists in my old database, then I have to get all the data and insert it again into my new sqlite file.

It looks like a slow process. My users don't want to lose data. Is there any other way that I can easily change the database of my existing application without losing any data.

+3


source to share


1 answer


First, you need to discover that the database is old. One way to do this is to have a table metadata

with name / value text columns ( value

is a reserved word, so use a different column name) and keep the current schema. If this does not exist, then you know an older version of it, but from now on you should constantly update this version of schenaVersion during these updates. You can store other information about the database itself in this table.

If the database is fundamentally different, then you need to use the second approach that you suggest:



  • Detect if the old version of the database if not abort the update.
  • Create a new database with a temporary file name. This includes setting up a new schema.
  • Open both databases at once.
  • Iterate through the tables in the old database and accept whatever values ​​are needed to populate the tables in the new database.
  • Close both databases.
  • Delete the old database file and move the new, temporary database file to the old, existing name.
  • Open the database and continue.

Alternatively, if the changes are not very different from each other, you can use the ALTER TABLE statement to change the schema. This is a much better approach, as it leaves the values ​​in place if the columns are not removed from the schema.

+1


source







All Articles