[英]Android and upgrading a database, is there a way I can use onUpgrade, or should I do my 'solution'. How does one test onUpgrade?
[英]How do I add a column in onUpgrade and set existing rows to a particular value?
如何在DatabaseHelper onUpgrade中添加列並將預先存在的行設置為特定值?
我試過了:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
...
if (oldVersion < 2) {
db.execSQL("ALTER TABLE " + MyTableName + " ADD COLUMN "
+ MyNewColumn + " TEXT;");
db.execSQL("UPDATE " + MyTableName + " SET " +
MyNewColumn + "=" + "value for existing;");
}
}
但是我不認為alter已經提交了,因為它說該列不存在。 有什么建議嗎?
編輯:添加了一些更多的周圍代碼
編輯:我的錯誤。 我只是錯過了關於值部分的引用,並且關於沒有列的錯誤讓我失望,但問題是它正在尋找我沒有引用的值使用的列。
添加一個列並不像你所示的那樣簡單,因為每次升級數據庫都會運行onUpgrade,第二次添加列會失敗...如果你想快速而又臟,你可以試一試抓住
try {
db.execSQL("ALTER TABLE sometable ADD COLUMN newcolumn integer");
}
catch(Exception e) {
e.printStackTrace();
}
更好的方法是將所有數據從表中移出到臨時表中,刪除並重新創建表並將數據重新放入。這是我之前使用的一個示例
//Update old Table
if(DBVER< 1060){
List<String> columns = DB.GetColumns(db, "listitems");
db.execSQL("ALTER table listitems RENAME TO 'temp_listitems); ") ;
String tblListItems = "create table if not exists listitems " +
"(id integer primary key autoincrement, " +
"listid integer, " +
"itemid integer, " +
"qty integer, " +
"collected integer, " +
"qtytype integer, " +
"tabid integer); " ;
db.execSQL(tblListItems);
columns.retainAll(DB.GetColumns(db, "listitems"));
String cols = DB.join(columns, ",");
db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", "listitems", cols, cols, "listitems"));
db.execSQL("DROP table 'temp_" + "listitems");
}
下面是http://www.devdaily.com/android/sqlite-alter-table-syntax-examples的鏈接
db.execSQL("ALTER TABLE " + MyTableName + " ADD "
+ MyNewColumn + " TEXT;");
不用Column就試試:語法是:
ALTER TABLE [TABLE_NAME] ADD [COLUMN_NAME] DATATYPE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.