How to manage database changes while upgrading desktop applications?
We have a SQLite database for one of our desktop apps. The uninstaller keeps the database to be used by the next install. But what if the next install has an updated version? How to keep the data but upgrade the tables?
We use .NET and Linq2sql
Here is how I do this:
In my code I define the version of the database
#define DB_VERSION 2
This version number is incremented every time I make a change to the code that 'breaks' the database ( makes an incompatible change to the schema or the semantics of the db contents )
When the code creates a new database, it executes this SQL command
QueryFormat(L"PRAGMA SCHEMA_VERSION = %d;",DB_VERSION);
Note that this must be AFTER all CREATE TABLE commands have been executed, otherwise sqlite increments SCHEMA_VERSION.
When the code opens an existing database, the first thing it does is
Query(L"PRAGMA schema_version;")
The SCHEMA_VERSION that is returned from this query is compared with the DB_VERSION. If they do not match, then the database was created by a different software version. What happens next depends on the details of what you need. Typically:
database was created by a more recent software: inform user and exit
database was created by older software for which there is an upgrade: offer user option to run upgrade code, or re-initialize database
database was created by older software with no upgrade: offer user option to re-initialize database or exit.
The details of how the upgrade code works depends very much on what you need. In general open the old database AND open a new empty database. Read the old tables, convert the data as required, and write to the new database. Close the dbs. Delete the old db. Rename the new db to the standard db name. Open the new db.
If nothing else, the output of echo .dump | sqlite my_database.sqlite
is designed to be extremely portable, even to non-SQLite databases.
Or, if I'm misreading your question, you may want alter table.
来源:https://stackoverflow.com/questions/5663380/how-to-manage-desktop-file-database-versions