Due to the application upgrade, often accompanied by database upgrade, database Upgrade general Design table additions and deletions, table add delete fields, data backup and other operations.
1. Database Upgrade
We all inherit the Sqliteopenhelper class, implement the database operation and version upgrade, and so on. Version upgrade related methods Onupgrade (sqlitedatabase db, int oldversion, int newversion);
The Onupgrade method is called when the version number is greater than the current database version number.
2. Demo Database Upgrade
It is relatively simple to add or delete a table, and the following demonstrates adding a field.
2.1 Raw Database SQL
private static final String sql= "CREATE TABLE IF not EXISTS" +table+ "("
+ "ID integer primary key autoincrement,"
+ "Name varchar"
+ ")";
For two field IDs, name;
2.2 Steps
Modify the original table name--Create a new table--Copy the original table data to a new table--Delete the original table
2.3 Code
1 Private voidupgradetable (sqlitedatabase db,string tablename) {2 //1. Modify the original table name ALTER TABLE TABLENAME Rename to Newtablename;3 db.begintransaction ();4String newtablename=tablename+ "_temp";5String sql= "ALTER TABLE" + tablename + "Rename to" +Newtablename;6 log.i (tag,sql);7 db.execsql (SQL);8LOG.I (TAG, tablename+ "--->" +newtablename);9 Ten //2. Create a new table with the table named TableName OneString newsql= "CREATE TABLE IF not EXISTS" +tablename+ "(" A+ "ID integer primary key autoincrement," -+ "name varchar," -+ "Age integer" the+ ")"; - - Db.execsql (newsql); -LOG.I (TAG, tablename+ "created successfully"); + - //3. Copying Data +String copysql= "INSERT INTO" +tablename+ "(id,name)" + "Select Id,name from" +Newtablename; A Db.execsql (copysql); atLOG.I (TAG, "Data copy succeeded"); - - //4. Delete temporary tables -String deletesql= "drop table IF EXISTS" +Newtablename; - Db.execsql (deletesql); -LOG.I (TAG, newtablename+ "Delete succeeded"); in - to db.settransactionsuccessful (); + db.endtransaction (); -}