Android Database upgrade, data not lost solution

Source: Internet
Author: User

Assuming that you want to update the TableC table, the recommended practice is to:

1) Rename the TableC to Tablec_temp

The SQL statement can be written like this: ALERT TABLE TableC RENAME to Tablec_temp;

2) Create a new TableC table

3) inserting data from the tablec_temp into the TableC table

SQL statements can be written like this: INSERT into TableC (Col1, Col2, Col3) SELECT (Col1, Col2, Col3) from Tablec_temp;


After these three steps, the TableC has completed the update, and the data in the original table has been preserved.

Attention:

In the Onupgrade () method, when you delete a table, pay attention to using transactions so that the modifications can immediately react to the database file.

protected voidupgradetables (sqlitedatabase db, String tableName, string columns) {Try{db.begintransaction (); //1, Rename table. String temptablename = tableName + "_temp"; String SQL= "ALTER TABLE" + tableName + "RENAME to" +Temptablename; EXECSQL (DB, SQL,NULL); //2, Create table. oncreatetable (DB); //3, Load datasql = "INSERT into" + TableName + "(" + Columns + ")" + "select" + Columns + "FR OM "+Temptablename; EXECSQL (DB, SQL,NULL); //4, Drop the temporary table. Execsql (db, "DROP TABLE IF EXISTS" + temptablename,NULL);      Db.settransactionsuccessful (); }      Catch(SQLException e) {e.printstacktrace (); }      Catch(Exception e) {e.printstacktrace (); }      finally{db.endtransaction (); }  }  

Android Database upgrade, data not lost solution

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.