Android Database Upgrade Solution

Source: Internet
Author: User

Turn from:http://blog.csdn.net/leehong2005/article/details/9128501

Please consider the following situation:

In the database upgrade, different versions of the database, they define the table structure may be not the same, such as V1.0 table A has 10 columns, and in V1.1 table A has 12 colum, when the upgrade, table A added two column, at this time we should do.

General Ideas

1, the table a renamed, changed the A_temp.

2, create a new table.

3. Insert data from table a_temp into table A.

The following code lists the implementation of the Update table, Upgradetables, given the table name, updated column name, you can implement the database table updates.

[Java]View Plaincopy
  1. /**
  2. * Upgrade tables. In this method, the sequence is:
  3. * <b>
  4. * <p>[1] Rename The specified table as a temporary table.
  5. * <p>[2] Create a new table which name is the specified name.
  6. * <p>[3] Insert data into the new created table, data from the temporary table.
  7. * <p>[4] Drop the temporary table.
  8. * </b>
  9. *
  10. * @param db the database.
  11. * @param tableName the table name.
  12. * @param columns The columns range, format is "ColA, ColB, Colc, ... Coln ";
  13. */
  14. protected void Upgradetables (Sqlitedatabase db, String tableName, string columns)
  15. {
  16. Try
  17. {
  18. Db.begintransaction ();
  19. //1, Rename table.
  20. String temptablename = tableName + "_temp";
  21. String sql = "ALTER TABLE" + tableName +"RENAME to" + temptablename;
  22. EXECSQL (DB, SQL, null);
  23. //2, Create table.
  24. Oncreatetable (DB);
  25. //3, Load data
  26. sql = "INSERT into" + TableName +
  27. " (" + columns + ")" +
  28. "Select" + Columns + "from" + temptablename;
  29. EXECSQL (DB, SQL, null);
  30. //4, Drop the temporary table.
  31. Execsql (db, "DROP TABLE IF EXISTS" + temptablename, null);
  32. Db.settransactionsuccessful ();
  33. }
  34. catch (SQLException e)
  35. {
  36. E.printstacktrace ();
  37. }
  38. catch (Exception e)
  39. {
  40. E.printstacktrace ();
  41. }
  42. finally
  43. {
  44. Db.endtransaction ();
  45. }
  46. }

Get the column name of the database table

We can get the column name of the table through the SQL table. One thing to note here is that int columnindex = C.getcolumnindex ("name"); Here the index is obtained according to the name.

[Java]View Plaincopy
  1. Protected string[] Getcolumnnames (sqlitedatabase db, String tableName)
  2. {
  3. string[] ColumnNames = null;
  4. Cursor C = null;
  5. Try
  6. {
  7. c = db.rawquery ("PRAGMA table_info (" + TableName + ")", null);
  8. if (null! = c)
  9. {
  10. int columnindex = C.getcolumnindex ("name");
  11. if (-1 = = columnindex)
  12. {
  13. return null;
  14. }
  15. int index = 0;
  16. ColumnNames = new String[c.getcount ()];
  17. For (C.movetofirst ();!c.isafterlast (); C.movetonext ())
  18. {
  19. Columnnames[index] = c.getstring (columnindex);
  20. index++;
  21. }
  22. }
  23. }
  24. catch (Exception e)
  25. {
  26. E.printstacktrace ();
  27. }
  28. finally
  29. {
  30. Closecursor (c);
  31. }
  32. return columnnames;
  33. }

The Upgradetables method should be called in the Onupgrade method.

The significance of database upgrade

In the application development process, the database upgrade is a very important component (if the database is used), Because the program may have v1.0,v2.0, when the user installs the new version of the program, must ensure that the user data can not be lost, for the database design, if changes occur (such as adding a table, table fields increase or decrease, etc.), then we must think good database update policy.

1, defining the database version

The version of the database is an integer value that is passed to the version of the database when the Sqliteopenhelper is created, and if the incoming database version number is larger than the version number stored in the database file, then the Sqliteopenhelper#onupgrade () method is called , our upgrade should be done in this method.

2, how to write upgrade logic

If we have developed a program that has been released in two versions: v1.0,v1.2, we are developing V1.3. The database version number for each edition is 18,19,20.

In this case, how should we implement the upgrade?

The user's choices are:

1) V1.3 DB, V1.0, 20

2) 20 V1.1, V1.3 DB

3, note

Each version of the database represents the database must be defined, such as V18 database, it may have only two tables TableA and TableB, if V19 to add a table TableC, if V20 to modify TableC, then each version of the database structure is as follows:

V18---> TableA, TableB

V19---> TableA, TableB, TableC

V20---> TableA, TableB, TableC (change)

The Onupgrade () method is implemented as follows:

[Java]View Plaincopy
  1. //Pattern for upgrade blocks:
  2. //
  3. if (upgradeversion = = [the database_version you set]-1) {
  4. //        .. Your upgrade logic.
  5. UpgradeVersion = [the database_version you set]
  6. //    }
  7. Public void Onupgrade (sqlitedatabase db, int oldversion, int newversion)
  8. {
  9. int upgradeversion = oldversion;
  10. if (= = = upgradeversion) {
  11. //Create table C
  12. String sql = "CREATE TABLE ...";
  13. Db.execsql (SQL);
  14. UpgradeVersion = 19;
  15. }
  16. if (= = upgradeversion) {
  17. //Modify table C
  18. UpgradeVersion = 20;
  19. }
  20. if (upgradeversion! = newversion) {
  21. //Drop Tables
  22. Db.execsql ("DROP TABLE IF EXISTS" + tableName);
  23. //Create Tables
  24. OnCreate (DB);
  25. }
  26. }


As you can see from the code above, in the Onupgrade () method, we process the upgrade of the database version from 20 to 20, whether the user is from 20, the database of the final program can be upgraded to the corresponding database structure of V20.

4, how to ensure that data is not lost

This is an important part, assuming that you want to update the TableC table, we recommend the following:

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.

SQL statements

Since Android uses open source SQLite3 as its database, we must be aware of the key words, functions, and so on, which are supported by SQLite3 when developing database modules.

Some reference links are listed below:

SQLite3 Official document:http://sqlite.org/

W3cschool website:http://www.w3school.com.cn/sql/index.asp/

The SQL statement can directly affect the operation of the database. I've encountered SQL statements that affect query performance, update 3,000 records, and 30 move around, but performance increases to 3-4 seconds after the fields of the Where condition are indexed.

Reference: http://androidll.iteye.com/blog/1570943

Android Database Upgrade 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.