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

Android 學習筆記:SQLite 資料庫入門與 CRUD 完整示範

編輯:關於 Android 開發

Android 學習筆記:SQLite 資料庫入門與 CRUD 完整示範

前陣子學了 Android 的幾種資料儲存方式:檔案、SharedPreferences,以及最有特色的 SQLite。老實說我很意外——Android 居然內嵌了一個輕量級資料庫,讓本地資料持久化有了質的飛躍。以下把課堂所學與課後閱讀整理成一篇筆記,方便日後複習。

一、SQLiteOpenHelper:官方提供的管理捷徑

為了讓我們更省事地管理資料庫,Android 提供 SQLiteOpenHelper 這個抽象類別。繼承它並實作兩個抽象方法:

  • onCreate():資料庫首次建立時觸發,通常用來建表。
  • onUpgrade():版本升級時觸發,用來做結構變更與資料維護。

另外兩個關鍵的實例方法是 getReadableDatabase() 與 getWritableDatabase(),兩者都會「有就開、沒有就建」,並回傳可操作資料庫的物件。差異在例外處理:當資料庫無法寫入(例如磁碟已滿)時,getReadableDatabase() 會以唯讀方式開啟,而 getWritableDatabase() 直接丟例外。一般情況下兩者拿到的物件都具備讀寫能力。

構造函數有四個參數:Context(操作資料庫的必備前提)、資料庫名稱、Cursor 工廠(通常傳 null)、以及版本號(升級判斷用)。

呼叫 getReadableDatabase() 或 getWritableDatabase() 之後,資料庫檔會落在 /data/data/<package name>/databases 目錄下,同時覆寫的 onCreate() 也會被執行。

二、SQLite 的資料型別

SQLite 不像其他資料庫有一堆繁雜型別,常用的就四種:integer(整數)、real(浮點數)、text(文字)、blob(二進位)。

三、用 adb shell 檢查資料庫內容

建好的資料庫檔在 File Explorer 裡看得到,但看不到裡面的表與資料,這時就得靠 adb shell。設定好 adb 環境變數後,開命令提示字元輸入 adb shell 進入環境,接著:

cd /data/data/<package name>/databases   # 進入目錄
ls                                       # 列出檔案
sqlite3 <資料庫名>                       # 進入 SQL 編輯模式
.table                                   # 查看有哪些表
.schema                                  # 查看建表語句

提醒:在 sqlite 編輯模式下,每句指令結尾都要加分號。

四、建立自己的 OpenHelper

package com.example.databasetest;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SqlOpenHelper extends SQLiteOpenHelper {

    public static final String CREATE_BOOK = "create table book("
            + "id integer primary key autoincrement, "
            + "name text,"
            + "price real)";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
    }

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

可以看到我們在 onCreate() 中呼叫 execSQL() 建了 book 表。

五、四顆按鈕搞定 CRUD

主介面放四顆按鈕,分別對應新增、更新、刪除、查詢:

<LinearLayout 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:orientation="vertical" >

    <Button
        android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="CREATE_BOOK"/>
    <Button
        android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="update"/>
    <Button
        android:id="@+id/btn3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="delete"/>
    <Button
        android:id="@+id/btn4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="select"/>
</LinearLayout>
package com.example.databasetest;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button btn1, btn2, btn3, btn4;
    private SqlOpenHelper helper;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        helper = new SqlOpenHelper(this, "book_store", null, 1);

        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn4 = (Button) findViewById(R.id.btn4);

        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                db = helper.getWritableDatabase();
                db.beginTransaction();          // 開始交易
                try {
                    ContentValues values = new ContentValues();
                    values.put("name", "Android");
                    values.put("price", 16.5);
                    values.put("category_id", "1");
                    db.insert("book", null, values);
                    db.setTransactionSuccessful();  // 標記交易成功
                    Toast.makeText(this, "Create Success", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    db.endTransaction();            // 結束交易
                    db.close();
                }
                break;

            case R.id.btn2:
                db = helper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("name", "zhangsan");
                values.put("price", 20);
                db.update("book", values, "id=?", new String[]{5 + ""});
                break;

            case R.id.btn3:
                db = helper.getWritableDatabase();
                db.delete("book", "id=?", new String[]{1 + ""});
                break;

            case R.id.btn4:
                db = helper.getWritableDatabase();
                Cursor cursor = db.query("book", null, null, null, null, null, "id DESC");
                while (cursor.moveToNext()) {
                    String name  = cursor.getString(cursor.getColumnIndex("name"));
                    String price = String.valueOf(cursor.getFloat(2));
                    Log.d("MainActivity", name);
                    Log.d("MainActivity", price);
                }
                break;

            default:
                break;
        }
    }
}

六、四個操作各自怎麼寫

新增:使用三參數的 insert()——表名、空欄位規則(一般填 null)、以及 ContentValues 物件。ContentValues 用 put() 以鍵值對形式存放資料。

更新:使用四參數的 update()——表名、新的 ContentValues、where 條件、條件參數陣列。後兩者以佔位符組成條件:

db.update("book", values, "id=?", new String[]{5 + ""});
// id=? 中的 ? 由第四個參數代入
// 若兩者都填 null,則更新全部資料列
// 回傳值為受影響的列數

刪除:delete() 三個參數,後兩個用法與 update 相同。

查詢:最複雜的一種。query() 回傳 Cursor,用 moveToNext() 逐列取出。雖然它收七個參數,但其實平常用只需要第一個(表名)與最後一個(排序方式)。七個參數的含義如下圖:

特別提醒新增時用到了交易:交易內的操作要嘛全做、要嘛全不做,可以確保資料一致性。另外每次操作資料庫前,都先用 helper 的 getWritableDatabase() 開啟(或建立)並取得可操作物件。

七、也可以直接寫 SQL

上述 API 的好處是即使不熟 SQL 也能操作資料庫,但 execSQL() 與 rawQuery() 讓你保留直接下指令的自由:

// 新增
db.execSQL("insert into book(name,price) values('haha',23)");
db.execSQL("insert into book(name,price) values(?,?)", new String[]{"haha", "34"});

// 更新
db.execSQL("update book set name=? where id=?", new String[]{"pig", 2 + ""});

// 刪除
db.execSQL("delete from book where id>?", new String[]{"3"});

// 查詢(第二個參數為查詢條件)
db.rawQuery("select * from book", null);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved