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
- /**
- * Upgrade tables. In this method, the sequence is:
- * <b>
- * <p>[1] Rename The specified table as a temporary table.
- * <p>[2] Create a new table which name is the specified name.
- * <p>[3] Insert data into the new created table, data from the temporary table.
- * <p>[4] Drop the temporary table.
- * </b>
- *
- * @param db the database.
- * @param tableName the table name.
- * @param columns The columns range, format is "ColA, ColB, Colc, ... Coln ";
- */
- protected void Upgradetables (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 data
- sql = "INSERT into" + TableName +
- " (" + columns + ")" +
- "Select" + Columns + "from" + 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 ();
- }
- }
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
- Protected string[] Getcolumnnames (sqlitedatabase db, String tableName)
- {
- string[] ColumnNames = null;
- Cursor C = null;
- Try
- {
- c = db.rawquery ("PRAGMA table_info (" + TableName + ")", null);
- if (null! = c)
- {
- int columnindex = C.getcolumnindex ("name");
- if (-1 = = columnindex)
- {
- return null;
- }
- int index = 0;
- ColumnNames = new String[c.getcount ()];
- For (C.movetofirst ();!c.isafterlast (); C.movetonext ())
- {
- Columnnames[index] = c.getstring (columnindex);
- index++;
- }
- }
- }
- catch (Exception e)
- {
- E.printstacktrace ();
- }
- finally
- {
- Closecursor (c);
- }
- return columnnames;
- }
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
- //Pattern for upgrade blocks:
- //
- if (upgradeversion = = [the database_version you set]-1) {
- // .. Your upgrade logic.
- UpgradeVersion = [the database_version you set]
- // }
- Public void Onupgrade (sqlitedatabase db, int oldversion, int newversion)
- {
- int upgradeversion = oldversion;
- if (= = = upgradeversion) {
- //Create table C
- String sql = "CREATE TABLE ...";
- Db.execsql (SQL);
- UpgradeVersion = 19;
- }
- if (= = upgradeversion) {
- //Modify table C
- UpgradeVersion = 20;
- }
- if (upgradeversion! = newversion) {
- //Drop Tables
- Db.execsql ("DROP TABLE IF EXISTS" + tableName);
- //Create Tables
- OnCreate (DB);
- }
- }
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