好的,在遇到更大的问题之前,您应该知道SQLite在ALTERTABLE命令上是有限的,它允许
add
和
rename
所以建议升级:
-
开始移动
-
使用运行表创建
if not exists
(我们正在进行升级,因此表可能还不存在,它将失败并删除)
-
将现有列放入列表中
List<String> 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
)
-
设置事务成功
(这不会处理表降级,如果重命名列,则不会传输现有数据,因为列名不匹配)。
.
public static List<String> GetColumns(SQLiteDatabase db, String tableName) {
List<String> ar = null;
Cursor c = null;
try {
c = db.rawQuery("select * from " + tableName + " limit 1", null);
if (c != null) {
ar = new ArrayList<String>(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<String> 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();
}