Upgrade the database version---keep the original data while upgrading the app

Source: Internet
Author: User

modifying table definitions

The SQLite number Library has very limited support for ALTER TABLE commands, only adding columns at the end of the table, cannot modify the column definition, and cannot delete existing columns. So what if you want to modify the table? We can use the temporary table approach. Specifically, there are four steps:

    1. Rename an existing table to a temporary table;

    2. Create a new table;

    3. Import data from the staging table into a new table (Note that the modified column is processed);

    4. Deletes a temporary table.

Take the example of V2 upgrade to V3 as an example:

public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {  if (oldversion==2) {    Db.execsql ("AlterTABLE t_region RENAMETo T_region_temp");  Db.execsql ("CREATETABLE T_region (_idIntegerPrimaryKey"  + "AutoIncrement, Regionvarchar, codevarchar "   +" Country  varchar)    Db.execsql ("insert into t_region (_id, Region, code, country)  "   +" select _id, Region, code, \ "china\" from t _region_temp ");    Db.execsql ("drop table t_region_temp }}           /span>                

Upgrade the database version---preserve the original data when you upgrade the app

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.