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

從零開始學 Android:數據存儲(四)SQLite 數據庫完整實戰

編輯:關於 Android 程式設計

前面幾章我們分別學習了 SharedPreferences 屬性文件存儲、內部存儲與外部存儲。這一章來看看 Android 內建的輕量級數據庫——SQLite。

一、先認識 SQLiteOpenHelper

SQLiteDatabase 本身只是一個數據庫操作類,真正要開展工作還需要一個 SQLiteOpenHelper 來幫忙創建與打開。而 SQLiteOpenHelper 是抽象類,使用時必須定義子類並覆寫相應的抽象方法。

常用方法:

  • SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version):構造方法,指明數據庫名與版本號
  • close():關閉數據庫
  • getReadableDatabase():以只讀方式創建或打開數據庫
  • getWritableDatabase():以讀寫方式創建或打開數據庫
  • onCreate(SQLiteDatabase db):創建數據表(抽象)
  • onOpen(SQLiteDatabase db):打開數據庫
  • onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):更新數據表(抽象)

三個關鍵回調:

  1. onCreate():第一次使用數據庫時調用,用來建表。注意它不是在實例化 Helper 對象時調用,而是在第一次調用 getReadableDatabase() 或 getWritableDatabase() 時才會觸發。
  2. onUpgrade():數據庫版本號提升時調用。通常在此刪除舊表,然後調用 onCreate() 重新建表。
  3. onOpen():數據庫打開時調用,一般不需要覆寫。

二、示例一:創建數據庫

佈局文件:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="108dp"
        android:text="建立數據庫" />

</RelativeLayout>

讓一個類繼承 SQLiteOpenHelper 並覆寫方法:

public class SqlIteOpenHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "flyou";        // 數據庫名稱
    public static final int VERSION = 2;                // 數據庫版本
    public static final String TABLENAME = "user_info"; // 數據表名稱

    public SqlIteOpenHelper(Context context) {
        super(context, DBNAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE " + TABLENAME + " ("
                + "id INTEGER PRIMARY KEY ,"
                + "name VARCHAR(50) NOT NULL ,"
                + "birthday DATE NOT NULL)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
        onCreate(db);
    }
}

只要調用一次 getWritableDatabase(),SQLite 就會在應用的 /data/data/<包名>/databases/ 目錄下生成 flyou 這個數據庫文件,並執行 onCreate() 建表。

數據庫文件生成後的位置:


三、示例二:用 SQL 語句做增刪改

Helper 代碼與上一節相同,另寫一個專門的操作類來封裝數據訪問:

public class Operator {

    private SQLiteDatabase db = null;

    public Operator(SQLiteDatabase db) {
        this.db = db;
    }

    /** 數據插入 */
    public void insert(String name, String birthday) {
        String sql = "insert into " + SqlIteOpenHelper.TABLENAME
                + " (name,birthday) Values(?,?)";
        Object args[] = { name, birthday };
        db.execSQL(sql, args);
    }

    /** 數據更新 */
    public void upDate(int id, String name, String birthday) {
        String sql = "update " + SqlIteOpenHelper.TABLENAME
                + " set name=?,birthday=? where id=?";
        Object args[] = { id, name, birthday };
        db.execSQL(sql, args);
    }

    /** 數據刪除 */
    public void delete(int id) {
        String sql = "delete from " + SqlIteOpenHelper.TABLENAME + " where id=?";
        Object args[] = { id };
        db.execSQL(sql, args);
    }
}

execSQL(sql, args) 這種帶占位符的寫法要優於字符串拼接——既能規避 SQL 注入,也能正確處理引號等特殊字符。

操作完成後把數據庫文件拉出來查看:


四、示例三:用 SQLiteDatabase 自帶的 CRUD 方法

除了寫 SQL,SQLiteDatabase 還提供了 insert()、update()、delete() 這組方法,配合 ContentValues 使用:

public class Operator {

    private SQLiteDatabase db = null;

    public Operator(SQLiteDatabase db) {
        this.db = db;
    }

    /** 插入數據 */
    public void insert(String name, String birthday) {
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("birthday", birthday);
        db.insert(Helper.TABLENAME, null, cv);
    }

    /** 更新數據 */
    public void upDate(String name, String birthday, int id) {
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("birthday", birthday);
        String whereClause = "id=?";
        String whereArgs[] = { String.valueOf(id) };
        db.update(Helper.TABLENAME, cv, whereClause, whereArgs);
    }

    /** 刪除數據 */
    public void delete(int id) {
        String whereClause = "id=?";
        String whereArgs[] = { String.valueOf(id) };
        db.delete(Helper.TABLENAME, whereClause, whereArgs);
    }
}

Activity 中通過按鈕觸發:

insert.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        helper = new Helper(MainActivity.this);
        database = helper.getWritableDatabase();
        new Operator(database).insert("房澤龍", "1992-03-18");
        database.close();
    }
});

運行效果與導出後的數據:

由於點擊了多次插入,可以看到裡面已經累積了多條數據。


五、查詢:Cursor 的使用

查詢結果由 Cursor 封裝,常用方法有:

  • close():關閉查詢
  • getCount():返回查詢到的數據總量
  • getColumnCount():返回結果的列數
  • getColumnNames() / getColumnName(int):獲取列名
  • isAfterLast() / isBeforeFirst() / isFirst() / isLast() / isClosed():指針位置判斷
  • moveToFirst() / moveToLast() / moveToNext() / moveToPrevious():指針移動
  • getXxx(int columnIndex):按列索引取值,如 getInt()、getString()

遍歷結果集的標準寫法:

for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {
    // 循環體
}

完整示例的佈局:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="插入數據" />

    <Button android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_centerHorizontal="true"
        android:text="更新數據" />

    <Button android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button2"
        android:layout_alignBottom="@+id/button2"
        android:layout_toRightOf="@+id/button2"
        android:text="刪除數據" />

    <Button android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignRight="@+id/button3"
        android:layout_below="@+id/button1"
        android:text="全部查詢" />

    <Button android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button4"
        android:layout_below="@+id/button4"
        android:text="模糊查詢" />

    <EditText android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button4"
        android:ems="10" >
        <requestFocus />
    </EditText>

    <ListView android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button5"
        android:layout_centerHorizontal="true" >
    </ListView>

</RelativeLayout>

操作類中新增兩個查詢方法:

/** 查找全部數據 */
public List<String> findAll() {
    List<String> all = new ArrayList<String>();
    String columns[] = { "id", "name", "birthday" };
    Cursor result = this.db.query(Helper.TABLENAME, columns, null, null, null, null, null);

    for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {
        all.add("[" + result.getInt(0) + "]--"
                + result.getString(1) + "--" + result.getString(2));
    }
    result.close();
    return all;
}

/** 模糊查詢 */
public List<String> findBy(String keyword) {
    List<String> all = new ArrayList<String>();
    String sql = "select * from " + Helper.TABLENAME
            + " where name like ? or birthday like ? or id like ?";
    String contexstr[] = {
            "%" + keyword + "%",
            "%" + keyword + "%",
            "%" + keyword + "%"
    };
    Cursor result = this.db.rawQuery(sql, contexstr);

    for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {
        all.add("[" + result.getInt(0) + "]--"
                + result.getString(1) + "--" + result.getString(2));
    }
    result.close();
    return all;
}

這裡演示了兩種查詢方式:db.query() 是方法參數式 API,db.rawQuery() 則直接吃 SQL 語句。前者更規範,後者更靈活——模糊查詢這種多字段 OR 的場景用 rawQuery 寫起來清爽不少。兩者都支持 ? 占位符。

界面展示:


六、幾個實務要點

  • Cursor 和 Database 都要關。示例中每個方法都調用了 close(),這不是可選項——Cursor 持有的是游標資源,不及時關閉會導致內存洩漏,量大了還會拋 CursorLeaked 相關異常。更好的做法是使用 try-with-resources(Cursor 實現了 Closeable)。
  • 不要在主線程做數據庫操作。示例為了簡潔把 CRUD 直接寫在 onClick() 裡,真實項目中應該放到子線程或 AsyncTask / 線程池裡,否則數據量大時會 ANR。
  • 版本升級要謹慎。示例裡的 onUpgrade() 直接 DROP 重建,這會清空用戶數據。正式產品中應該寫遷移邏輯(ALTER TABLE ADD COLUMN、或新建表 + 拷貝數據 + 改名)。
  • 分頁查詢與事務處理限於篇幅不再展開,學過 Java 的讀者應該不難上手——分頁用 limit offset,事務用 beginTransaction() / setTransactionSuccessful() / endTransaction(),注意事務要在 endTransaction() 之前設置成功標記。

另外,如果數據量較大或需要複雜的關係建模,可以考慮 ORM 框架(Room、GreenDAO)來減少樣板代碼;Room 還自帶了編譯期 SQL 校驗與與 LiveData / Flow 的響應式集成。

下節預告:意圖 Intent

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