woff 發表於 2018-2-8 18:13:00

SQLite在Android下增加新的columns

在寫App時,會用到sqlite當資料庫

但app會一直更新

所以資料庫欄位也會增加

這時如何讓使用者無痛更新呢?

假設我要再現有資料庫資加一個欄位

在呼叫sqlite時最上端會用到這行
public MyDB(Context context) {
      super(context, SQL_NAME, null, 1);
    }

這時找到這一函式
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      switch (oldVersion) {
            case 1:
                String ALTER_TBL =
                              "ALTER TABLE " + TABLE_NAME +
                              " ADD COLUMN kkk text;";
                db.execSQL(ALTER_TBL);
                break;
    }這時把1改成2
public MyDB(Context context) {
super(context, SQL_NAME, null, 2);
}

當APP運行時
就會多一欄位 kkk
如圖


如果我要刪除columns時,又該如何處理呢?
首先先把table改名
然後建新new_table
把table資料copy 到new_table
這樣就可以了

實作
建新的table
CREATE TABLE team(Name TEXT, Coach TEXT, City TEXT)
等等把 city 欄位改成Location

步驟1: 更名原始 table為team_orig:
ALTER TABLE team RENAME TO team_orig;


步驟 2: 建置新的替代table有:Name , Coach , Location

CREATE TABLE team(Name TEXT, Coach TEXT, Location TEXT);
步驟 3: 複製資料從舊table到新table

INSERT INTO team(Name, Coach, Location) SELECT Name, Coach, City FROM team_orig;
Note: The above command should be all one line.

步驟 4: 刪除舊 table:

DROP TABLE team_orig;


參考資料
https://stackoverflow.com/questions/27878905/upgrade-sqlite-database-in-my-app
https://blog.xojo.com/2013/12/04/renaming-columns-in-sqlite-tables/
頁: [1]
查看完整版本: SQLite在Android下增加新的columns