[英]Database error using new version on upgrade
I am adding a column to a DB in the onUpgrade()
method which works fine on devices / emulators where the previous DB version exists. 我在
onUpgrade()
方法中向数据库添加一列,该方法在存在先前数据库版本的设备/仿真器上可以正常工作。
However when installing on devices for first time I get an error starting the column (in on upgrade()) can't be found. 但是,当第一次在设备上安装时,出现错误,无法找到启动列(在upgrade()上)。
I am assuming this is because the device can't find a previous version so the onUpgrade()
is not executed. 我认为这是因为设备找不到以前的版本,所以不会执行
onUpgrade()
。
Is there a way around this? 有没有解决的办法?
Cheers 干杯
Here is the code: 这是代码:
@Override
public void onCreate(SQLiteDatabase db) {
// only called once when DB first created, takes DB as arg
db.execSQL("CREATE TABLE "+ DATABASE_TABLE + " ("+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_DIVELOCATION + " TEXT , "+
KEY_DIVESITE + " TEXT , " +
KEY__DIVENUMBER + " INTEGER DEFAULT 0 , " +
KEY__DIVEDATE + " TEXT , " +
KEY_DIVERATING + " FLOAT DEFAULT 0.0 , " +
KEY_BOTTOMTIME + " INTEGER DEFAULT 0 , " +
KEY_DIVEBUDDY + " TEXT , " +
KEY__DIVECENTER + " TEXT , " +
KEY_ENDBAR + " INTEGER DEFAULT 0 , " +
KEY_STARTBAR + " INTEGER DEFAULT 0 , " +
KEY_VIZIBILTY + " INTEGER DEFAULT 0 , " +
KEY_WATERTEMP + " INTEGER DEFAULT 0, " +
KEY_COMMENTS + " TEXT , " +
KEY_CONDITIONS + " TEXT , " +
KEY_DIVEPICTURE + " TEXT );"
);
//use for dtabase querys
columns = new String[]{KEY_ROWID, KEY_DIVERATING, KEY_BOTTOMTIME, KEY_DIVEBUDDY,
KEY__DIVECENTER, KEY_DIVELOCATION,
KEY__DIVENUMBER, KEY_DIVESITE, KEY_ENDBAR, KEY_STARTBAR,
KEY_VIZIBILTY, KEY_WATERTEMP,KEY__DIVEDATE,
KEY_COMMENTS, KEY_CONDITIONS, KEY_DIVEPICTURE};
}//end onCreate DB inner helper class
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if table exits, drop it (delete) and recreate it to upgrade it
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
//need to call upgrade and add a int column for depth, newVersion is 2
if (newVersion> oldVersion ){
db.execSQL("ALTER TABLE "+DATABASE_TABLE+" ADD COLUMN "+KEY_DEPTH+" INTEGER DEFAULT 0");
}
onUpgrade will be only called when a version of database will gets old. 仅当数据库版本变旧时才调用onUpgrade。 ie you change the version which you passes during database creation.
即,您更改在数据库创建过程中传递的版本。
eg 例如
super(context, DATABASE_NAME, null,DATABASE_VERSION);
Now if DATABASE_VERSION is changed, only then onUpgrade will gets called... 现在,如果更改了DATABASE_VERSION,则只有onUpgrade会被调用...
So i think, you just need to execute your create table commands in onCreate
and only use commands of changing tables in onUpgrade
. 所以我认为,您只需要在
onCreate
执行创建表命令,而仅在onUpgrade
使用更改表的命令即可。 That way you won't have this issue. 这样,您就不会遇到这个问题。
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.