When the Android app is updated, if the database modifies the field, the database needs to be updated and the original database data is retained:
This is the original database table.
Create_book = "CREATE TABLE book (BookId integer primarykey,bookname text);";
We then add a field:
Create_book = "CREATE TABLE book (BookId integer primarykey,bookname text,bookcontent text);";
First, we need to rename the original database table.
Create_temp_book = "ALTER TABLE book rename to _temp_book";
Then copy the data from the backup table into the newly created database table
Insert_data = "INSERT INTO book SELECT *, ' from _temp_book"; (note ' is the default value for the newly added field must be added, otherwise it will be an error).
Then we'll just kill the backup table.
Drop_book = "drop table _temp_book";
After the database version is modified, the database Operation object will be updated automatically when it is updated (note: The first action data created when updating the object must be writable, that is, through this method Getwritabledatabase () Gets the database Operation object)
Then executing the above SQL statement in the Onupgrade () method is OK.
public class Dbservice extends sqliteopenhelper{
Private String Create_book = "CREATE table book (bookId integer primarykey,bookname text);";
Private String Create_temp_book = "ALTER TABLE book rename to _temp_book";
Private String Insert_data = "INSERT into book select *, ' from _temp_book";
Private String Drop_book = "DROP table _temp_book";
Public Dbservice (Context context, String name, cursorfactory factory,int version) {
Super (context, name, Factory, version);
}
@Override
public void OnCreate (Sqlitedatabase db) {
Db.execsql (Create_book);
}
@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
Switch (newversion) {
case 2:
db.execsql (create_temp_book);
db.execsql (Create_book);
db.execsql (Insert_data);
db.execsql (Drop_book);
break;
}
}