小编典典
好的,在遇到更大的问题之前,您应该知道SQLite受到ALTER
TABLE命令的限制,它仅允许add并且rename不允许通过重新创建表进行删除/删除操作。
您应该始终手头有新的表创建查询,并将其用于升级和传输任何现有数据。注意:onUpgrade方法为sqlite辅助对象运行一个,并且您需要处理其中的所有表。
那么建议在Upgrade上进行以下操作:
beginTransaction
使用运行表创建if not exists(我们正在进行升级,因此该表可能尚不存在,更改和删除将失败)
将现有列放在列表中 List columns = DBUtils.GetColumns(db, TableName);
备用表(ALTER table " + TableName + " RENAME TO 'temp_" + TableName)
创建新表(最新的表创建模式)
获取与新列的交集,这次列取自升级表(columns.retainAll(DBUtils.GetColumns(db, TableName));)
恢复数据(String cols = StringUtils.join(columns, ","); db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TableName, cols, cols, TableName));)
删除备份表(DROP table 'temp_" + TableName)
setTransactionSuccessful
。
public static List GetColumns(SQLiteDatabase db, String tableName) {
List ar = null;
Cursor c = null;
try {
c = db.rawQuery("select * from " + tableName + " limit 1", null);
if (c != null) {
ar = new ArrayList(Arrays.asList(c.getColumnNames()));
}
} catch (Exception e) {
Log.v(tableName, e.getMessage(), e);
e.printStackTrace();
} finally {
if (c != null)
c.close();
}
return ar;
}
public static String join(List list, String delim) {
StringBuilder buf = new StringBuilder();
int num = list.size();
for (int i = 0; i < num; i++) {
if (i != 0)
buf.append(delim);
buf.append((String) list.get(i));
}
return buf.toString();
}
2020-09-15