我们在当前的应用程序中实现了一个ormlite解决方案。我们使用它来缓存来自服务器的rest调用的结果。所以,数据在那里(或者当用户更新应用程序时留下来)不是特别重要。我们刚刚添加了一个更新,它在我们的一个数据库持久化模型中创建了一个新列,我们现在看到以下异常:
Caused by: android.database.sqlite.SQLiteException: no such column: acknowledged (code 1): , while compiling: SELECT * FROM ...
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1430)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1369)
at com.j256.ormlite.android.AndroidCompiledStatement.getCursor(AndroidCompiledStatement.java:162)
at com.j256.ormlite.android.AndroidCompiledStatement.runQuery(AndroidCompiledStatement.java:57)
at com.j256.ormlite.stmt.SelectIterator.<init>(SelectIterator.java:55)
at com.j256.ormlite.stmt.StatementExecutor.buildIterator(StatementExecutor.java:232)
at com.j256.ormlite.stmt.StatementExecutor.query(StatementExecutor.java:181)
at com.j256.ormlite.dao.BaseDaoImpl.query(BaseDaoImpl.java:263)
我检查以确保该字段被添加到ormlite配置文件中,并且确实是,所以我不确定这里发生了什么。我以为ormlite会删除数据库并在发现模式已更改时重新创建它(并且您没有向
Shift
添加onUpgrade()
方法),但我现在认为我是不正确的。我该怎么解决?我试过阅读ormlite手册,但要么我忽略了关于默认升级行为的部分,要么我没有找到它…
最佳答案
我以为ormlite会删除数据库并在发现模式已更改时重新创建它(并且您没有向databasehelper添加onupgrade()方法),但我现在认为我不正确。
你错了。ormlite没有任何处理模式更新的神奇代码。查看手册中upgrading your schema的文档。引述:
升级应用程序时,可能需要添加列或对应用程序以前版本存储的数据进行其他更改。如果您在android上,那么在databasehelper中,应该有onupgrade()方法从ormlitesqliteopenhelper扩展以下方法。
abstract void onUpgrade(SQLiteDatabase database,
ConnectionSource connectionSource, int oldVersion, int newVersion)
在该方法中,您可以使用DAO对架构执行任何调整:
Dao<Account, Integer> dao = getHelper().getAccountDao();
// change the table to add a new column named "age"
dao.executeRaw("ALTER TABLE `account` ADD COLUMN age INTEGER;");
所以你需要自己升级。这些文档还显示了如何使用数据库版本号根据客户端的数据库版本进行特定更改。
如果您不关心现有的表,那么
onUpgrade(...)
方法可以直接删除表并调用onCreate(...)
。