1.首先我们需要把原来的数据库表重命名一下
public static final String TEMP_SQL_CREATE_TABLE_SUBSCRIBE = "alter table "
+ A + " rename to temp_A";
原来的表结构是:
private static final String SQL_CREATE_TABLE_SUBSCRIBE = "create table if not exists "
+ A + "(id integer primary key autoincrement,code text not null,name text,username text)";
2.然后把备份表temp_A中的数据copy到新创建的数据库表A中,这个表A没发生结构上的变化
public static final String INSERT_SUBSCRIBE = "select 'insert into A (code,name,username,tablename)
values ('''||code||''','''||name||''',''cnki'','''||tablename||'''')' as insertSQL from temp_A";
3.此时临时表中的数据已经全部复制到了表A中,但是我之前的表A中有四条默认的数据,用户可能删了,可能又增加了新的数据,那我不管用户什么操作,我都把这4条删除掉,然后重新添加一次,这样就保证了之前的四条数据还在新的数据表中。
这是我之前的四条数据,我先找出来:
public static final String[] arrWhereAct = {
"where code ='K174' and tablename = 'phonepaper'",
"where code ='GMRB' and tablename = 'newspaper'",
"where code ='XJSJ' and tablename = 'magazine'",
"where code ='JTKL' and tablename = 'magazine'" };
4.删除备份表
public static final String DELETE_TEMP_SUBSCRIBE = "delete from temp_A ";
public static final String DROP_TEMP_SUBSCRIBE = "drop table if exists temp_A";
5.然后把数据库版本号改为比之前高的版本号,在OnUpgrade方法中执行上述语句就行,具体如下:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (int j = oldVersion; j <= newVersion; j++) {
switch (j) {
case 2:
//创建临时表
db.execSQL(TEMP_SQL_CREATE_TABLE_SUBSCRIBE);
//执行OnCreate方法,这个方法中放的是表的初始化操作工作,比如创建新表之类的
onCreate(db);
//删除之前的表里面的那4条默认的数据
for (int i = 0; i < arrWhereAct.length; i++) {
db.execSQL(DELETE_TEMP_SUBSCRIBE + arrWhereAct[i]);
}
//将临时表中的数据放入表A
Cursor cursor = db.rawQuery(INSERT_SUBSCRIBE, null);
if (cursor.moveToFirst()) {
do {
db.execSQL(cursor.getString(cursor
.getColumnIndex("insertSQL")));
} while (cursor.moveToNext());
}
cursor.close();
//将临时表删除掉
db.execSQL(DROP_TEMP_SUBSCRIBE);
break;
default:
break;
}
}
}
为什么要在方法里写for循环,主要是考虑到夸版本升级,比如有的用户一直不升级版本,数据库版本号一直是1,而客户端最新版本其实对应的数据库版本已经是4了,那么我中途可能对数据库做了很多修改,通过这个for循环,可以迭代升级,不会发生错误。