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

Android 數據存儲之 SQLite 數據庫詳解

編輯:關於 Android 程式設計

SQLite 是一款輕量級的關系型數據庫,運算速度極快、占用資源極少,通常只需幾百 K 內存便足夠,因而特別適合移動設備。它不僅支持標準 SQL 語法,還遵循 ACID(原子性、一致性、隔離性、持久性)事務。只要用過其他關系型數據庫,就能快速上手 SQLite。相比一般數據庫,它甚至無需設置用戶名和密碼即可使用。Android 正是把這個功能強大的數據庫嵌入系統,讓本地持久化實現了一次質的飛躍。

一、創建數據庫

為方便管理數據庫,Android 提供了 SQLiteOpenHelper 幫助類。它有多個構造方法,一般使用參數較少的那個即可,接收四個參數:Context、數據庫名、查詢時返回的自定義 Cursor(通常傳 null)、以及當前數據庫版本號(用於升級)。

例如:MyDatabaseHelper(context, "BookStore.db", null, 1);

public class MyDatabaseHelper extends SQLiteOpenHelper {
    public static final String CREATE_BOOK = "create table book ("
            + "id integer primary key autoincrement, "
            + "author text, "
            + "price real, "
            + "pages integer, "
            + "name text)";
    private Context mContext;

    public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}

二、升級數據庫

MyDatabaseHelper 中那個空方法 onUpgrade() 用於數據庫升級,作用不可小覷。假如項目中已有一張 Book 表,現在想再添加一張 Category 表記錄書籍分類,該怎麼做?

public class MyDatabaseHelper extends SQLiteOpenHelper {
    public static final String CREATE_BOOK = "create table Book ("
            + "id integer primary key autoincrement,"
            + "author text, "
            + "price real, "
            + "pages integer, "
            + "name text)";
    public static final String CREATE_CATEGORY = "create table Category ("
            + "id integer primary key autoincrement,"
            + "category_name text, "
            + "category_code integer)";
    private Context mContext;

    public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext, "create successed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
        Toast.makeText(mContext, "刪除數據", Toast.LENGTH_SHORT).show();
    }
}

把版本號從 1 改成 2,即可觸發升級邏輯。

三、添加數據

使用 ContentValues 組裝數據,再調用 insert 插入:

SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "The Da Vinci Code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
db.insert("Book", null, values);

四、更新數據

ContentValues values = new ContentValues();
values.put("price", 10.99);
db.update("Book", values, "name = ?", new String[] { "The Da Vinci Code" });

這句話等價於 Update Book set price=10.99 where name='The Da Vinci Code'。

五、刪除數據

db.delete("Book", "pages > ?", new String[] { "500" });

等價於 delete from Book where pages>500。

六、查詢數據

Cursor cursor = db.query("Book", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
    do {
        String name = cursor.getString(cursor.getColumnIndex("name"));
        String author = cursor.getString(cursor.getColumnIndex("author"));
        int pages = cursor.getInt(cursor.getColumnIndex("pages"));
        double price = cursor.getDouble(cursor.getColumnIndex("price"));
        Log.d("MainActivity", "book name is " + name);
        // ...
    } while (cursor.moveToNext());
}
cursor.close();

通過 moveToFirst() 定位首行,再用 do-while 遍歷 Cursor 逐條取出數據。

七、使用原生 SQL 操作數據庫

除了封裝方法,也可以直接寫 SQL:

添加:

db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",
    new String[] { "The Da Vinci Code", "Dan Brown", "454", "16.96" });

更新:

db.execSQL("update Book set price = ? where name = ?",
    new String[] { "10.99", "The Da Vinci Code" });

刪除:

db.execSQL("delete from Book where pages > ?", new String[] { "500" });

查詢:

db.rawQuery("select * from Book", null);

可見除查詢用 rawQuery() 外,其餘操作都調用 execSQL()。兩種方式效果一致,選哪種全憑個人喜好。

八、使用事務

想象一個轉賬場景:銀行先從你的賬戶扣款,再向收款方賬戶加等量的錢。若扣款成功後因異常導致對方收款失敗,這筆錢就憑空消失了。銀行當然充分考虑了這種情況——它會保證扣錢與收款要麼一起成功、要麼都不成功,靠的就是事務。

SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction(); // 開啟事務
try {
    db.delete("Book", null, null);
    if (true) {
        // 手動拋出異常,讓事務失敗
        throw new NullPointerException();
    }
    ContentValues values = new ContentValues();
    values.put("name", "Game of Thrones");
    values.put("author", "George Martin");
    values.put("pages", 720);
    values.put("price", 20.85);
    db.insert("Book", null, values);
    db.setTransactionSuccessful(); // 事務執行成功
} catch (Exception e) {
    e.printStackTrace();
} finally {
    db.endTransaction(); // 結束事務
}

只有調用了 setTransactionSuccessful(),事務才會真正提交;一旦中途拋出異常,之前的操作全部回滾。

九、升級數據庫的最佳實踐

最初只需一張 Book 表:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}

幾週後需要新增 Category 表,於是在 onUpgrade 中按版本遞增處理:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
        case 1:
            db.execSQL(CREATE_CATEGORY);
        default:
    }
}

不久又要給 Book 表添加 category_id 字段建立關聯:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
        case 1:
            db.execSQL(CREATE_CATEGORY);
        case 2:
            db.execSQL("alter table Book add column category_id integer");
        default:
    }
}

這裡有一個至關重要的細節:switch 中每個 case 的最後都故意不寫 break。這樣做是為了保證跨版本升級時每一次修改都能被完整執行。若用戶從第 2 版升到第 3 版,只執行 case 2;若直接從第 1 版升到第 3 版,則 case 1 與 case 2 都會執行。採用這種方式維護升級,無論版本如何更新,都能保證表結構始終最新,且原有數據不會丟失。

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