Upgrade: Overriding the Onupgrade method
- Determine the difference between adjacent versions, starting from version 1 to iterate over the update, first execute V1 to v2, then v2 to v3 ...
- For each version determine the difference from the current database, write a special upgrade code for each case.
Downgrade
Ondowngrade () database demotion: For example, downgrading from database 4 to database 3 must override this method.
@Override Public void int int newversion) { super. Ondowngrade (db, Oldversion, newversion); }
Migrating data:
- Rename an existing table to a temporary table;
- Create a new table;
- Import data from the staging table into a new table (Note that the modified column is processed);
- Deletes a temporary table.
protected voidupgradetables (sqlitedatabase db, String tableName, string columns) {Try{db.begintransaction (); //1. Rename an existing table to a temporary tableString temptablename = tableName + "_temp"; String SQL= "ALTER TABLE" + tableName + "RENAME to" +Temptablename; EXECSQL (DB, SQL,NULL); //2, create a new table//oncreatetable (db);Createnewtablex (DB); //3. Import temporary table data into a new tablesql = "INSERT into" + TableName + "(" + Columns + ")" + "select" + Columns + "FR OM "+Temptablename; EXECSQL (DB, SQL,NULL); //4. Delete temporary tablesExecsql (db, "DROP TABLE IF EXISTS" + temptablename,NULL); Db.settransactionsuccessful (); } Catch(SQLException e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } finally{db.endtransaction (); } }
Android--Interview--Database upgrade strategy