什么是升级sqllite分贝的正确方法? [英] what is the correct way to upgrade sqllite db?
问题描述
private static final String TABLE_MAIN_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_MAIN_NAME + " ( a INTEGER, b LONG, c TEXT, d TEXT, e DATETIME, f TEXT)";
private static final String TABLE_MAIN_UPGRADE = "ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column f TEXT";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_MAIN_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < newVersion) {
db.execSQL(TABLE_MAIN_UPGRADE);
}
onCreate(db);
}
在previous数据库的版本是不带F字段中。 这是升级数据库的正确方法? 难道我在onUpgrade需要的onCreate(DB)?
The previous db version was without the "f" field. Is this the correct way to upgrade the DB? Do I need onCreate(db) in onUpgrade?
我这样做了几次,每次都让我有另外一个例外: 1)表已经存在,所以我说IF NOT EXISTS 2)看不懂行0,第5栏的错误在这里我失去了它......
I did this several times and each time I got another exception: 1) table already exists so I added "IF NOT EXISTS" 2) could not read row 0, col 5 error here I lost it....
这是升级数据库的正确方法?
IS this the correct way to upgrade the db?
我要保持我的数据
推荐答案
您需要做的事情取决于 oldVersion
...
you have to do something depends on oldVersion
...
FX:你可以分贝版本从10-14,上了年纪那么10你不瓦纳的支持,并在每个新版本中添加新列code应该看起来像(动态网页为14):
fx: you can have db versions from 10-14, the older then 10 you dont wana support and at every new version you add a new column the code should looks like(newVersion is 14):
private static final String TABLE_MAIN_CREATE_14 =
"CREATE TABLE IF NOT EXISTS " + TABLE_MAIN_NAME +
" ( a INTEGER, b LONG, c TEXT, d TEXT, e DATETIME, f TEXT, g TEXT, h TEXT, i TEXT)";
private static final String TABLE_MAIN_UPGRADE_10_11 =
"ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column f TEXT";
private static final String TABLE_MAIN_UPGRADE_11_12 =
"ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column g TEXT";
private static final String TABLE_MAIN_UPGRADE_12_13 =
"ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column h TEXT";
private static final String TABLE_MAIN_UPGRADE_13_14 =
"ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column i TEXT";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_MAIN_CREATE_14);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion){
case 10: // from 10 to 11 and go to next case
db.execSQL(TABLE_MAIN_UPGRADE_10_11);
case 11: // from 11 to 12 and go to next case
db.execSQL(TABLE_MAIN_UPGRADE_11_12);
case 12: // from 12 to 13 and go to next case
db.execSQL(TABLE_MAIN_UPGRADE_12_13);
case 13: // from 13 to newVersion
db.execSQL(TABLE_MAIN_UPGRADE_13_14);
break;
default:
//not upgratable too old - so we should drop and recreate;
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MAIN_NAME );
onCreate(db);
break;
}
}
编辑:嗯,好像有人有他个人的事情,我和downvoting这个答案,那么成熟:)
edit: hmmm, seems like someone has something personal to me and downvoting this answer, so mature :)
这篇关于什么是升级sqllite分贝的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!