bug: 用户使用旧版本app 版本2.2.0 升级最新版本 3.3.7 数据库错误 影响app使用
eg: 现版本 oldVersion = 47 存在建表操作且后续对表添加新字段
app更新阶段
47 → 48 → 49 → 50 逐步升级:正常
47 → 50 跳版本升级: 数据库初始化错误
猜测
实体类在代码中已经包含了新增的字段
你在 v47 调用 TableUtils.createTable(...) 时,ORMlite 会根据当前类的定义创建表,直接包含新建字段
v49 的 upgrade 逻辑中又试图手动 ALTER TABLE ... ADD xx
列已存在 可能 ALTER TABLE ADD COLUMN 失败,抛出 SQLite 异常!
为兼容跨版本升级的用户
private void addColumnIfNotExists(SQLiteDatabase db, String tableName, String columnName, String columnType) {
if (!columnExists(db, tableName, columnName)) {
String sql = "ALTER TABLE " + tableName + " ADD COLUMN " + columnName + " " + columnType;
db.execSQL(sql);
}
}
/**
* 判断指定表中是否包含某列
*/
private boolean columnExists(SQLiteDatabase db, String tableName, String columnName) {
try (Cursor cursor = db.rawQuery("PRAGMA table_info(" + tableName + ")", null)) {
if (cursor != null) {
int nameIndex = cursor.getColumnIndex("name");
while (cursor.moveToNext()) {
if (cursor.getString(nameIndex).equalsIgnoreCase(columnName)) {
return true;
}
}
}
}
return false;
}
只需要在所有 ALTER TABLE ADD COLUMN 操作前,加上「列是否存在」的判断,就能安全支持任意跳版本升级(如 30 → 50)

被折叠的 条评论
为什么被折叠?



