How to update sqlite on iPhone app
I have an iPhone application that uses a sqlite3 database for saving data and before I release the app I need to be sure that some of the tables data (that the user has saved) must be copi开发者_如何学Ced to the new database.
How should I manage this migration. I was thinking about separating the database and the queries. Is that bad? So when the app opens I check if the database is in the document folder, if not copy the database and run the queries in the separate file. Then when it is a new version I check the version number and run just the queries in the file (which update the data and alter some of them), and not copy the database?
One way of doing this is to have a table in your database that contains a schema version of the database.
Once a user have a database in the documents folder (which was probably copied from a premade database from the app bundle) you should make changes to that database to keep it in sync with the current schema. This includes upgrading the schema and any changed data.
You can do this by bundling a number of sql scripts in your app that will bring the users database schema forward one step at a time, e.g.:
- Read schema version from users database => 3 (current is 5)
- Execute sql script "schema_3_to_4.sql"
- Execute sql script "schema_4_to_5.sql"
- All done - ready to use
If you don't have a schema version in your current db, just regard this as version 0 and add the table in your version 1 update, e.g:
begin exclusive transaction;
create table schema (version integer);
insert into schema(version) values (1);
create table temp_update as select * from question;
drop table question;
create table question(id INTEGER PRIMARY KEY, new_answer INTEGER);
insert into question(id, new_answer) select id, 42 from temp_update;
drop table temp_update;
commit;
I think that the best approach is migrating from a manual handling of the sqlite3 database to a Core-Data-based one. Core Data provides you with a lot of tools for defining and modelling data, including a super easy (when available) lightweight migration process that will incredibly ease the data migration process between various data base versions.
Using a lightweight migration (or the more complex custom manual migration) your problems will be automatically solved.
精彩评论