Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

淺談 Android 資料庫版本升級與資料遷移

編輯:關於 Android 程式設計

Android 上的 SQLite 輕量好用,簡單設定用 SharedPreferences 就夠,只有資料結構稍複雜時才需要資料庫。但表結構很少一次設計到位,App 迭代幾輪之後必然要改——這時就出現「升級」與「資料遷移」的難題。處理得差,使用者升級後會發現資料全空。

一、升級的幾種情況

• 新增表
• 刪除表
• 修改表
• 新增欄位/刪除欄位

新增與刪除表最簡單,不涉及資料遷移:前者 CREATE TABLE 即可,後者代表歷史資料不再需要,DROP TABLE 便了事。真正棘手的是修改表與增刪欄位。

很多開發者為了省事,直接在 onUpgrade 裡把舊表 drop 掉再重建。實作上確實最省事,但對使用者是災難:如果你正在下載一個 99% 的檔案,更新完發現下載列表空了,那個檔案就得從頭再來——這種體驗足以讓人直接卸载。

二、判斷升級路徑

SQLiteOpenHelper 的兩個回呼分工明確:

/**
 * Called when the database is created for the first time.
 */
public abstract void onCreate(SQLiteDatabase db);

/**
 * Called when the database needs to be upgraded.
 * @param oldVersion The old database version.
 * @param newVersion The new database version.
 */
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);

onCreate 只在首次建立時呼叫;onUpgrade 則帶入舊版號與新版號,是處理遷移的唯一入口。

本文以 ORMLite 為例。假設版本 1→2→3 之間,A 表加了欄位、B 表刪了欄位、C 表不變;升級到 3 時 C 再加一個欄位。

三、基本建置

三個資料類別:

@DatabaseTable(tableName = "tb_a")
public class A {
    @DatabaseField(generatedId = true) public int id;
    @DatabaseField public String name;
}

@DatabaseTable(tableName = "tb_b")
public class B {
    @DatabaseField(generatedId = true) public int id;
    @DatabaseField public String name;
    @DatabaseField public String age;
}

@DatabaseTable(tableName = "tb_c")
public class C {
    @DatabaseField(generatedId = true) public int id;
    @DatabaseField public String name;
}

Helper:

public class MySqliteHelper extends OrmLiteSqliteOpenHelper {

    private static final String DATABASE_NAME = "test.db";
    private static final int DATABASE_VERSION = 1;
    private static MySqliteHelper mInstance;

    public MySqliteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static MySqliteHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySqliteHelper(context);
        }
        return mInstance;
    }

    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource cs) {
        try {
            TableUtils.createTableIfNotExists(cs, A.class);
            TableUtils.createTableIfNotExists(cs, B.class);
            TableUtils.createTableIfNotExists(cs, C.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource cs,
                          int oldVersion, int newVersion) {
        // 遷移邏輯寫在這裡
    }
}

DAO 則各自包一層:

public class ADao {
    private Dao<A> dao;

    public ADao(Context context) {
        try {
            dao = MySqliteHelper.getInstance(context).getDao(A.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

第一次執行 DAO 操作時,test.db 建立完成並觸發 onCreate 建表。

四、暴力解法(不建議)

@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource cs,
                      int oldVersion, int newVersion) {
    if (oldVersion < 2) {
        try {
            TableUtils.dropTable(cs, A.class, true);
            TableUtils.dropTable(cs, B.class, true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    onCreate(db, cs);
}

程式碼很短,代價是使用者資料全滅。除非你的表裡存的都是可隨時重建的快取,否則不要這樣做。

五、真正的遷移:改名 → 建表 → 搬資料 → 刪臨時表

SQLite 不像 MySQL 有 ALTER COLUMN,增刪欄位的通用做法是「建新表、搬資料、換名」。核心工具類如下:

public class DatabaseUtil {

    public enum OPERATION_TYPE { ADD, DELETE }

    public static <T> void upgradeTable(SQLiteDatabase db, ConnectionSource cs,
                                        Class<T> clazz, OPERATION_TYPE type) {
        String tableName = extractTableName(clazz);
        db.beginTransaction();     // 用事務保證全成功或全失敗
        try {
            // 1. 舊表改名為臨時表
            String tempTableName = tableName + "_temp";
            db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tempTableName);

            // 2. 依新定義建新表
            try {
                String sql = TableUtils.getCreateTableStatements(cs, clazz).get(0);
                db.execSQL(sql);
            } catch (Exception e) {
                e.printStackTrace();
                TableUtils.createTable(cs, clazz);
            }

            // 3. 搬資料:欄位來源依操作類型而異
            String columns;
            if (type == OPERATION_TYPE.ADD) {
                // 新增欄位 → 以舊表(臨時表)的欄位為準,新欄位帶預設值
                columns = Arrays.toString(getColumnNames(db, tempTableName))
                                 .replace("[", "").replace("]", "");
            } else {
                // 刪除欄位 → 以新表的欄位為準
                columns = Arrays.toString(getColumnNames(db, tableName))
                                 .replace("[", "").replace("]", "");
            }
            db.execSQL("INSERT INTO " + tableName + " (" + columns + ") "
                     + "SELECT " + columns + " FROM " + tempTableName);

            // 4. 刪掉臨時表
            db.execSQL("DROP TABLE IF EXISTS " + tempTableName);

            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }

    private static <T> String extractTableName(Class<T> clazz) {
        DatabaseTable annotation = clazz.getAnnotation(DatabaseTable.class);
        if (annotation != null && annotation.tableName().length() > 0) {
            return annotation.tableName();
        }
        String name = JavaxPersistence.getEntityName(clazz);
        return (name == null) ? clazz.getSimpleName().toLowerCase() : name;
    }

    private static String[] getColumnNames(SQLiteDatabase db, String tableName) {
        Cursor cursor = null;
        String[] columnNames = null;
        try {
            cursor = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);
            if (cursor != null) {
                int columnIndex = cursor.getColumnIndex("name");
                if (columnIndex == -1) return null;
                columnNames = new String[cursor.getCount()];
                int index = 0;
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    columnNames[index++] = cursor.getString(columnIndex);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) cursor.close();
        }
        return columnNames;
    }
}

遷移實際產生的 SQL 長這樣:

-- A 表新增 age 欄位:以舊欄位為準
INSERT INTO tb_a (id, name) SELECT id, name FROM tb_a_temp;

-- B 表刪除 age 欄位:以新欄位為準
INSERT INTO tb_b (id, name) SELECT id, name FROM tb_b_temp;

於是 onUpgrade 中依版本號分階段處理:

@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource cs,
                      int oldVersion, int newVersion) {
    if (oldVersion < 2) {
        DatabaseUtil.upgradeTable(db, cs, A.class, DatabaseUtil.OPERATION_TYPE.ADD);
        DatabaseUtil.upgradeTable(db, cs, B.class, DatabaseUtil.OPERATION_TYPE.DELETE);
    }
    if (oldVersion < 3) {
        DatabaseUtil.upgradeTable(db, cs, C.class, DatabaseUtil.OPERATION_TYPE.ADD);
    }
    onCreate(db, cs);
}

這個寫法的關鍵在於用 if (oldVersion < N) 而非 if (oldVersion == N)。使用者可能從 1 直接跳到 3(兩個 if 都執行),也可能從 2 升到 3(只執行第二個 if),版本路徑必須全部覆蓋。若只是新增一張全新的表 D,在 onCreate 裡多一行 TableUtils.createTableIfNotExists(cs, D.class) 即可,別忘了把 DATABASE_VERSION 加一。

可以確認 A、B 兩表的歷史資料都還在。

六、這套方案的邊界

以上遷移假設「新舊欄位之間邏輯性不強」。如果遇到像 user_id 這種帶業務含義的新欄位——舊資料搬過去之後 user_id 是空的,而查詢時又必須用它當條件——那麼單靠預設值無法解決,必須依具體業務撰寫專屬的補資料邏輯(例如從其他表反查、或依下載任務的擁有者回填)。

三個實務建議:遷移前先備份(把舊 db 檔複製一份),出錯時至少能救回使用者資料;全程包在單一事務裡,避免搬到一半失敗留下半殘表;務必在真機上跑一遍「舊版本安裝 → 升級」的路徑,直接安裝新版的測試永遠測不到 onUpgrade。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved