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";
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);
}
//将临时表中的数据放入表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);