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

Android SQLite 常用操作整理:語法、Helper 與業務層封裝

編輯:關於 Android 程式設計

正式專案裡,多數人會直接採用 GreenDAO、Room 這類 ORM 框架來碰資料庫。但偶爾還是需要下來寫幾句原生 SQL,或是要 debug 框架產生的語法。這幾天剛好有空,把 SQLite 的常用操作重新梳理一遍。

SQLite 是一款輕量級的關聯式資料庫管理系統,遵守 ACID 特性、開源、可嵌入,由程式庫本身驅動而非獨立服務。它在 Android 上之所以好用,關鍵在於 API 簡單、樣板程式碼少。

資料型態

SQLite 採用動態型別,官方定義的五個儲存類別是:

  • NULL:空值。
  • INTEGER:有號整數,依數值大小以 1、2、3、4、6 或 8 位元組儲存。
  • REAL:浮點數,以 8 位元組 IEEE 浮點格式儲存。
  • TEXT:文字字串,依資料庫編碼(UTF-8、UTF-16BE、UTF-16LE)儲存。
  • BLOB:原始資料塊,完全按輸入內容存放,不做任何轉換。

實務上你寫 Integer、varchar、datetime、double 也不會報錯,SQLite 會依「型別親和性」規則盡量對應到上述五類。

常用 SQL 語法

建立與刪除資料表

create table 表名 (欄位名 型別 約束, 欄位名 型別 約束, ...)

-- 範例:建立學生表
create table student (_id Integer primary key, name varchar(10) not null, age Integer, score float)

-- 刪除資料表
drop table student

新增資料

-- 指定欄位(推薦,欄位順序不受限制)
insert into 表名 (欄位1, 欄位2, ...) values (值1, 值2, ...)

-- 不指定欄位,值必須與欄位「數量、順序完全一致」且不可有缺漏
insert into 表名 values (值1, 值2, ... 值n)

-- 範例
insert into student (_id, name, age, score) values (1, '張三', 13, 85.6)

刪除與修改

-- 刪除
delete from 表名 where 條件
delete from student where name = "張三"

-- 修改
update 表名 set 欄位 = 新值 where 條件
update student set score = 90 where _id = 1

提醒一句:where 子句若漏寫,delete 會清掉整張表、update 會改掉每一列,這在真實專案裡是災難級別的失誤。

查詢

-- 全部
select * from 表名

-- 指定欄位 + 條件 + 分組 + 排序
select 欄位名 from 表名
where 查詢條件
group by 分組欄位
having 篩選條件
order by 排序欄位

-- 範例:查張三的分數
select score from student where name = '張三'

完整範例

下面用一個小 Demo 把「建立資料庫 → 插入 → 查詢 → 刪除 → 修改」串起來,每按一次按鈕就重新查詢並把結果顯示在畫面上。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button db_create, table_insert, table_query, table_delete, table_update;
    private TextView show_tv;
    private boolean isCreateDb = false;
    private DBManager mDbManager;
    private MyDBHelper mDbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDbManager = DBManager.getInstance(this);
        mDbHelper = new MyDBHelper(this);
        initViews();
    }

    private void initViews() {
        db_create = findViewById(R.id.db_create);
        table_insert = findViewById(R.id.table_insert);
        table_query = findViewById(R.id.table_query);
        table_delete = findViewById(R.id.table_delete);
        table_update = findViewById(R.id.table_update);
        show_tv = findViewById(R.id.show_tv);

        db_create.setOnClickListener(this);
        table_insert.setOnClickListener(this);
        table_query.setOnClickListener(this);
        table_delete.setOnClickListener(this);
        table_update.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.db_create:
                if (mDbHelper == null) {
                    mDbHelper = new MyDBHelper(this);
                }
                isCreateDb = true;
                queryAndShow();
                break;

            case R.id.table_insert:
                if (!isCreateDb) {
                    Toast.makeText(this, "請先點擊按鈕創建數據庫相關信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                String[] sqls = {
                    "insert into " + MyDBHelper.T_NAME + " values(1,'趙一',14,99)",
                    "insert into " + MyDBHelper.T_NAME + " values(2,'吳二',15,67.5)",
                    "insert into " + MyDBHelper.T_NAME + " values(3,'李四',14,59)",
                    "insert into " + MyDBHelper.T_NAME + " values(4,'王五',15,80)",
                    "insert into " + MyDBHelper.T_NAME + " values(5,'陳六',16,77.5)",
                    "insert into " + MyDBHelper.T_NAME + " values(6,'劉大',15,83.4)"
                };
                for (String sql : sqls) {
                    mDbManager.execSql(mDbHelper.getWritableDatabase(), sql);
                }
                queryAndShow();
                break;

            case R.id.table_query:
                if (!isCreateDb) {
                    Toast.makeText(this, "請先點擊按鈕創建數據庫相關信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                queryAndShow();
                break;

            case R.id.table_delete:
                if (!isCreateDb) {
                    Toast.makeText(this, "請先點擊按鈕創建數據庫相關信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                mDbManager.execSql(mDbHelper.getWritableDatabase(),
                        "delete from " + MyDBHelper.T_NAME + " where " + MyDBHelper.TABLE_ID + "=3");
                queryAndShow();
                break;

            case R.id.table_update:
                if (!isCreateDb) {
                    Toast.makeText(this, "請先點擊按鈕創建數據庫相關信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                mDbManager.execSql(mDbHelper.getWritableDatabase(),
                        "update " + MyDBHelper.T_NAME + " set " + MyDBHelper.TABLE_NAME
                        + "='李九' where " + MyDBHelper.TABLE_ID + "=5");
                queryAndShow();
                break;
        }
    }

    /** 查詢並把結果攤平成文字顯示 */
    private void queryAndShow() {
        String sql = "select * from " + MyDBHelper.T_NAME;
        StringBuffer sb = new StringBuffer();
        Cursor cursor = mDbHelper.getWritableDatabase().rawQuery(sql, null);
        while (cursor.moveToNext()) {
            sb.append("_id=").append(cursor.getString(cursor.getColumnIndex(MyDBHelper.TABLE_ID))).append(" ")
              .append("name=").append(cursor.getString(cursor.getColumnIndex(MyDBHelper.TABLE_NAME))).append(" ")
              .append("age=").append(cursor.getInt(cursor.getColumnIndex(MyDBHelper.TABLE_AGE))).append(" ")
              .append("score=").append(cursor.getInt(cursor.getColumnIndex(MyDBHelper.TABLE_SCORE))).append("\n");
        }
        cursor.close();
        show_tv.setText("查詢結果是:\n" + sb.toString());
    }
}

SQLiteOpenHelper:把建表邏輯交給系統

除了手寫 SQL,Android 也提供了標準的資料庫操作方式。繼承 SQLiteOpenHelper,在 onCreate() 裡放建表語句即可:

public class MyDBHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "test";
    private static final int DB_VERSION = 1;

    public static final String T_NAME = "student";
    public static final String TABLE_ID = "_id";
    public static final String TABLE_NAME = "name";
    public static final String TABLE_AGE = "age";
    public static final String TABLE_SCORE = "score";

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

    public MyDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    /** 資料庫首次建立時回呼,在此執行建表語句 */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table " + T_NAME + "("
                + TABLE_ID + " Integer primary key,"
                + TABLE_NAME + " varchar(10),"
                + TABLE_AGE + " Integer,"
                + TABLE_SCORE + " float)";
        db.execSQL(sql);
    }

    /** 版本號提升時回呼,通常用來做 migrate */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 處理結構變更
    }

    /** 每次開啟資料庫都會回呼;若資料庫已存在,不會再走 onCreate */
    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
    }
}

把操作統一封裝起來

專案裡建議再包一層,讓「拿到 Helper」與「執行 SQL」這兩件事有單一入口,之後要換 ORM 或加 log 都只改一處:

public class DBManager {

    private static DBManager dbManager;
    private Context context;

    private DBManager(Context context) {
        this.context = context;
    }

    public static DBManager getInstance(Context context) {
        if (null == dbManager) {
            dbManager = new DBManager(context);
        }
        return dbManager;
    }

    /** 以 SQL 字串直接操作資料庫 */
    public void execSql(SQLiteDatabase db, String sql) {
        if (null != db && !TextUtils.isEmpty(sql)) {
            db.execSQL(sql);
        }
        db.close();
    }
}

版面與權限

主介面用五顆按鈕搭配一個顯示結果的 TextView 就夠了:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sqlite數據庫操作" />

    <Button android:id="@+id/db_create"    android:layout_width="match_parent" android:layout_height="wrap_content" android:text="創建數據庫" />
    <Button android:id="@+id/table_insert" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="表中插入數據" />
    <Button android:id="@+id/table_query"  android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查詢表中數據" />
    <Button android:id="@+id/table_delete" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="刪除表中數據" />
    <Button android:id="@+id/table_update" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="修改表中數據" />

    <TextView
        android:id="@+id/show_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textColor="@android:color/holo_blue_bright"
        android:textSize="15sp" />

</LinearLayout>

若資料庫要建在外部儲存空間,記得補上寫入權限:

<!-- 往 SDCard 寫入資料 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

執行結果:

最後提一個實務建議:上面的範例把 SQL 用字串拼接,示範上很直觀,但正式環境請改用參數化查詢(rawQuery(sql, selectionArgs) 或 ContentValues),避免使用者輸入被當成 SQL 片段執行,那是最常見的注入風險來源。

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