The database version upgrades the management operations of the software.
Our mobile phone will often receive the XXX software upgrade what the reminder, your software version updates, and your database corresponding version of the corresponding update.
Database version updates require major issues:
When the 1.0 version of the software is upgraded to version 1.1, the old data cannot be lost.
Then in the 1.1 version of the program will be able to detect the new version of the software is incompatible with the old database, and there is a way to upgrade the 1.0 software database to 1.1 software can use the database.
In other words, add that field to the table in the database of the 1.0 software and give the field the default value.
Of course, sometimes we do not have a good impression of the updated version, as well as the original version with the handy, then we will be downgraded to their own software operations.
The next step is an analysis of the version operation of the lifting level database.
When the system constructs an object of the Sqliteopenhelper class, if the version number is found to be different, the Onupgrade function is automatically called, allowing you to upgrade the database here.
Based on the above scenario, add fields to the corresponding tables of the old database in this function and add the default values to each record.
Both the new version number and the old version number are passed in as parameters to the Onupgrade function, making it easy for developers to know which version the database should be upgraded from.
When the upgrade is complete, the database automatically stores the latest version number for the current database version number.
v1.0 1. OnCreate () not installed--------------------------------------v2.0 [Onupgrade Condition: N-1,oncreate Condition: 1] 1.v1.0-v2.0Onupgrade2. OnCreate () not installed-----------------------------------------v3.0 [Onupgrade Condition: N-1,oncreate Condition: 1] 1. v1.0-->v3.0Onupgrade ALTER TABLE t_message add column Isdel bitdefault0; Inserting Data* 2. v2.0-->v3.0Onupgrade ALTER TABLE t_message add column Isdel bitdefault0; 3onCreate () degraded design key not installed1, consider the cloud to save users "custom data, behavior habits." Professional terminology profile-->>Increase user Viscosity2. Consider [current] minimum version requirements-->>Reduced maintenance costs3, as far as possible local data transfer (all new versions, do not delete fields)--as far as possible to know the unknownTry Catch
We use code to describe the operation of the version upgrade.
This mainactivity.class starts the database connection
PackageCom.example.testdb;Importandroid.app.Activity;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.os.Bundle; Public classMainactivityextendsActivity {protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //Create a databaseMydatabaseopenhelper helper =NewMydatabaseopenhelper (mainactivity. This); //Get database connectionSqlitedatabase db =helper.getwritabledatabase (); //Close the databaseDb.close (); } }
mainactivity
This is the whole code to run directly will be wrong below will say
PackageCOM.EXAMPLE.WINXINMFF;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper;ImportAndroid.util.Log; Public classMydatabaseopenhelperextendsSqliteopenhelper {/*** * Database version must be greater than 0, otherwise error: Unable to start activity * Java.lang.IllegalArgumentException:Version must is >= 1, was 0*/ Private Static FinalString db_name = "mydata.db";//Database name Private Static Final intVersion = 1;//Database Version// http://www.cnblogs.com/xinye/p/3481352.html PublicMydatabaseopenhelper (Context context) {Super(Context, Db_name,NULL, version); } //question: When to execute//No Previous//This method is called when the method database is first created. This is where the database tables and table initialization are created. //1, the first time to open the database will not walk (run)//2. After clearing the data, run again-open the database, this method will go//3, no clear data, do not go this way//4, the database upgrade time this method will not go Public voidonCreate (Sqlitedatabase db) {//write [start from 0 to latest State] Build table statementLOG.I ("Hi", "no database, create DATABASE, create v1.0 success"); String Sql_message= "CREATE table t_message (ID int primary KEY,TOU1 varchar (), userName varchar (), lastmessage varchar (), datetime varchar (50)) "; Db.execsql (Sql_message); /*String sql_init_1 = "INSERT into t_message values (1, ' abc ', ' Aaa1 ', ' 11.11 ', ' hi1 ')"; Db.execsql (sql_init_1); String sql_init_2 = "INSERT into t_message values (2, ' abc ', ' Aaa2 ', ' 11.11 ', ' hi1 ')"; Db.execsql (sql_init_2); String sql_init_3 = "INSERT into t_message values (3, ' abc ', ' Aaa3 ', ' 11.11 ', ' hi1 ')"; Db.execsql (sql_init_3);*/ } //v2.0 is now in progress//1, the first time you create a database, this method will not go//2, clear the data after the run again (equivalent to the first creation) This method will not go//3, the database already exists, and the version is raised, this method will be called Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { if(Oldversion = = 2) {String sql_upgrade_1= "ALTER TABLE t_message add column Isdel bit default 0;"; Db.execsql (sql_upgrade_1); LOG.I ("DB", "from 2 to 3, upgrade succeeded!" "); } if(Oldversion = = 1) {String sql_upgrade_1= "ALTER TABLE t_message add column Isdel bit default 0;"; Db.execsql (sql_upgrade_1); String sql_init_1= "INSERT into t_message values (1, ' abc ', ' Aaa1 ', ' 11.11 ', ' Hi1 ', 0)"; Db.execsql (sql_init_1); String sql_init_2= "INSERT into t_message values (2, ' abc ', ' Aaa2 ', ' 11.11 ', ' Hi1 ', 0)"; Db.execsql (sql_init_2); String Sql_init_3= "INSERT into t_message values (3, ' abc ', ' Aaa3 ', ' 11.11 ', ' Hi1 ', 0)"; Db.execsql (Sql_init_3); LOG.I ("DB", "from one to 3, upgrade success!" "); } } //analog reduced back to 2.0 from 3.0//perform a degraded operation of the database//1, only when the new version is lower than the old version will be executed//2. If you do not perform a downgrade operation, an exception will be thrown Public voidOndowngrade (Sqlitedatabase db,intOldversion,intnewversion) { //in normal terms greater than 2.0, there should be t_message this table, and 2.0 of the fields. 3.0. Try { //first, the t_message of the future of the table, renamedString rename_sql = "ALTER TABLE t_message rename to T_message_bak"; Db.execsql (Rename_sql); LOG.I ("Down", "1. Rename succeeded"); //second, the establishment of a 2.0 table structureString sql_message = "CREATE TABLE t_message (ID int primary KEY,TOU1 varchar (), userName varchar (), lastmessage varcha R (), DateTime varchar (50)) "; Db.execsql (Sql_message); LOG.I ("Down", "2. Build 2.0 Table Structure Success"); //Third, copy the backup data to the new 2.0 tableString sql_copy = "INSERT INTO T_message select Id,tou1,username,lastmessage,datetime from T_message_bak"; Db.execsql (sql_copy); LOG.I ("Down", "3.copy to user data to 2.0 table"); //IV. Drop the backup tableString drop_sql = "drop table if exists T_message_bak"; Db.execsql (Drop_sql); LOG.I ("Down", "4. Drop the Backup table"); } Catch(Exception e) {//failedLOG.I ("Hi", "downgrade failed, re-established"); String sql_drop_old_table= "DROP table if exists t_message"; Db.execsql (sql_drop_old_table); String Sql_message= "CREATE table t_message (ID int primary KEY,TOU1 varchar (), userName varchar (), lastmessage varchar (), datetime var CHAR (50)) "; Db.execsql (Sql_message); String sql_init_1= "INSERT into t_message values (1, ' abc ', ' ABC1 ', ' abcd1 ', ' hi1 ')"; Db.execsql (sql_init_1); String sql_init_2= "INSERT into t_message values (2, ' abc ', ' ABC2 ', ' abcd2 ', ' hi1 ')"; Db.execsql (sql_init_2); String Sql_init_3= "INSERT into t_message values (3, ' abc ', ' ABC2 ', ' abcd2 ', ' hi1 ')"; Db.execsql (Sql_init_3); } }}
Mydatabaseopenhelper
[1] Set the database version to 1
[2] INSERT statement Comment left only the statement that created the table
Now it's the first time you run the log and print out 32 lines.
Now let's take a look at the table.
Successfully created a table in version 1.0
See version 2.0
[1] Uninstallation program
[2] Set the database version to 2
[3] Remove the comment from the INSERT statement
Overriding the Export database view
The table was successfully created in version 2.0 with data inserted
From 2.0 to 3.0 versions (upgrade)
[1] Set the database version to 3
Logs that are running
Overriding the Export database view
Table structures successfully changed in version 3.0 are inserted by default to zero
Re-version from 3.0 to 2.0 (downgrade)
[1] Set the database version to 2
Logs that are running
Overriding the Export database view
Finally recommend a blog post http://www.cnblogs.com/xinye/p/3481352.html
Android Database upgrade, downgrade, create (OnCreate () Onupgrade () Ondowngrade ())