问题描述
我有一个简单的实体:
public class MyEntity extends SugarRecord {
String name;
int value;
public MyEntity() {
//empty ctr for sugar orm
}
public MyEntity(String name, int value) {
this.name = name;
this.value = value;
}
}
在App启动时,我创建一个实例并保存如下:
On App start I make an instance and save it like this:
Log.i("db_test", "count_before: "+MyEntity.count(MyEntity.class)+"");
new MyEntity("name", 10).save();
Log.i("db_test", "count_after: "+MyEntity.count(MyEntity.class)+"");
在日志中,我可以看到:
In the log I can see:
04-12 14:58:52.538: I/db_test(10691): count_before: 0
04-12 14:58:52.555: I/Sugar(10691): MyEntity saved : 1
04-12 14:58:52.555: I/db_test(10691): count_after: 1
运行良好.
那么,如果我决定要向MyEntity类添加属性,该怎么办?像这样:
So what if I decide I would like to add a property to MyEntity class. like this:
public class MyEntity extends SugarRecord {
String name;
int value;
int anotherValue; ///< A new property.
//...
此后,由于模型已更改,因此我增加了Databse版本.因此,我将清单中的以下字段从1增加到2.
After this I increment the Databse version because the model has changed.So I increase the following field in the manifest from 1 to 2.
<meta-data
android:name="VERSION"
android:value="2"/>
这一次,当我运行我的应用程序时,出现以下错误:
This time when i ran my app I got the following error:
E/SQLiteLog(11125): (1) table MY_ENTITY has no column named ANOTHER_VALUE
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}:
android.database.sqlite.SQLiteException: table MY_ENTITY has no column named ANOTHER_VALUE (code 1): , while compiling: INSERT OR REPLACE INTO MY_ENTITY(ANOTHER_VALUE,ID,VALUE,NAME) VALUES (?,?,?,?)
那为什么会这样呢?
我已经在Java对象上设置了此属性.
I have made this property on my Java object.
我已经增加了数据库版本.
I have incremented the database version.
我做错了什么
推荐答案
虽然这不是理想的解决方案,但使用升级文件手动更改表应该可以使插入/替换工作.
Whilst it's not an ideal solution, using an upgrade file to manually alter the table should allow the insert / replace to work.
AFAIK,VERSION值仅用于标识是否应运行补丁.
AFAIK, the VERSION value is only used to identify if patches should be run.
在您的情况下,可能是在您的assets/sugar_upgrades/
文件夹中添加了一个名为"2.sql"的文件,其中包含:
In your case, it would be a case of adding a file called "2.sql" into your assets/sugar_upgrades/
folder, containing:
ALTER TABLE my_entity ADD COLUMN another_value int;
来源: SugarORM
这篇关于如何使用Sugar Orm升级数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!