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

Android 資料儲存(三):SQLite 資料庫的建立與操作

編輯:關於 Android 程式設計

若要保存大量重複或結構化的資料,資料庫是最合適的選擇。Android 中 SQLite 相關的 API 都集中在 android.database.sqlite 套件裡,學習曲線平緩,但幾個慣例若不遵守,後續維護會很痛苦。

一、繼承 SQLiteOpenHelper

// 繼承 SQLiteOpenHelper 類
public class DictionaryOpenHelper extends SQLiteOpenHelper {

二、定義成員變數與常數

public static final String DABASENAME = "dictionary";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase mDatabase;
private Context mContext;

// 定義 table 相關的內容
/*
 * 實現 BaseColumns 接口,內部類中會有一個關鍵字 _ID。android 中的一些類希望有 _ID,
 * 例如 cursor,但它不是必須的,但能夠幫助數據庫和 android 框架更好地協調
 */
public static class DictionaryEntry implements BaseColumns {
    public static final String TAB_NAME = "words";
    public static final String COLUMN_WORD = "word";
    public static final String COLUMN_DEFINATION = "defination";
}

// 用於創建數據庫
private static final String SQL_CREATE_ENTRIES =
    "CREATE TABLE " + DictionaryEntry.TAB_NAME + "(" +
    DictionaryEntry._ID + " INTEGER PRIMARY KEY," +
    DictionaryEntry.COLUMN_WORD + "," +
    DictionaryEntry.COLUMN_DEFINATION + ")";

public DictionaryOpenHelper(Context context) {
    super(context, DABASENAME, null, DATABASE_VERSION);
}

讓資料表定義實作 BaseColumns 是官方建議的做法,這樣 Cursor 等元件能與 Android 框架更好地協調。

三、實作 SQLiteOpenHelper 的回呼

// 當第一創建數據庫時會被調用
@Override
public void onCreate(SQLiteDatabase db) {
    // db.execSQL(SQL_CREATE_ENTRIES);
    // 讀取文件並添加多行
    loadDictionary();
}

private void loadDictionary() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            loadWords();
        }
    });
}

private void loadWords() {
    // 讀取資源
    final Resources resources = mContext.getResources();
    InputStream inputStream = resources.openRawResource(R.raw.definitions);
    Scanner scanner = new Scanner(inputStream);
    while (scanner.hasNextLine()) {
        String string = scanner.nextLine();
        String[] strings = string.split("-");
        if (strings.length < 2) {
            continue;
        }
        loadWord(strings[0].trim(), strings[1].trim());
    }
}

// 添加行
private void loadWord(String word, String defination) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(DictionaryEntry.COLUMN_WORD, DictionaryEntry.COLUMN_DEFINATION);
    mDatabase.insert(DictionaryEntry.TAB_NAME, null, contentValues);
}

// 當數據庫升級的時候會被調用
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL(SQL_CREATE_ENTRIES);
    onCreate(db);
}

兩點提醒:資料庫檔案存放在內部儲存,其他應用程式無法存取,安全性有基本保障;另外,getWritableDatabase() 與 getReadableDatabase() 涉及磁碟 I/O,不該放在主執行緒做長時間操作,應改用 AsyncTask 或 IntentService 之類的後台機制。

四、寫入資料

// 1. 創建 ContentValues 對象並添加信息
ContentValues contentValues = new ContentValues();
contentValues.put(DictionaryEntry.COLUMN_WORD, DictionaryEntry.COLUMN_DEFINATION);
// 2. 添加到數據庫中
mDatabase.insert(DictionaryEntry.TAB_NAME, null, contentValues);

五、查詢資料

使用 query() 檢索資料,回傳一個 Cursor 物件:

mDatabase.query(
    table,        // table 名
    columns,      // 返回的關鍵字
    selection,    // where 語句的關鍵字
    selectionArgs,// where 的值
    groupBy,      // 用於聲明怎麼去組織行
    having,       // 用於聲明哪個行組應該包含到 Cursor 中
    orderBy);     // 按哪個關鍵字排序

六、刪除與更新

刪除資料時必須提供 selection 條件,否則會清掉整張表:

mDatabase.delete(
    table,      // table 名
    whereClause,// 用於操作的 WHERE 子句
    whereArgs); // WHERE 子句的參數

更新資料則用 update():

mDatabase.update(
    table,      // 要更新的 table 名
    values,     // ContentValues 的對象,用於指定更新的數據
    whereClause,// where 子句,用於指定哪一個行(記錄)需要修改
    whereArgs); // where 子句的值

七、用 sqlite3 除錯

Android SDK 內建 sqlite3 工具,可以直接查看資料庫表中的內容,操作全在命令列完成:

~$ adb devices
List of devices attached
emulator-5554   device

~$ adb -s emulator-5554 shell
#sqlite3 /data/data/com.example.mydictionary/databases/dictionary
sqlite> .table

進到 sqlite 提示符號後,就能用 SQL 語法檢視與修改資料。這個工具在驗證 insert 是否真的成功時特別有用,比反覆加 Log 有效率得多。

參考資料:
https://developer.android.com/training/basics/data-storage/databases.html
https://developer.android.com/guide/topics/data/data-storage.html

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