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

Android 內建 SQLite 資料庫實戰:從 openOrCreateDatabase 到 SQLiteOpenHelper

編輯:關於 Android 程式設計

SQLite 是 Android 內嵌的關聯式資料庫,體積小、功能足以應付多數 SQL 操作,本質上就是一個檔案。但它畢竟不像 PC 上的 MySQL 那樣強大,而且 Android 不允許透過 JDBC 連線遠端資料庫,若需要伺服器資料,只能走 WebService 與後端(PHP、Servlet 等)溝通。

基礎:SQLiteDatabase

SQLiteDatabase 類別代表一個資料庫物件,所有操作都經由它進行。常用的開啟/建立方法:

  • openDatabase(String path, CursorFactory factory, int flags)
  • openOrCreateDatabase(File file, CursorFactory factory)
  • openOrCreateDatabase(String path, CursorFactory factory)

執行 SQL 的方法:

  • execSQL(String sql, Object[] bindArgs)/execSQL(String sql)
  • rawQuery(String sql, String[] selectionArgs)
  • beginTransaction()/endTransaction()

查詢結果以 Cursor 表示,性質近似 JDBC 的 ResultSet,可用 moveToFirst()、moveToLast()、moveToNext()、moveToPosition(int)、move(offset)、moveToPrevious() 移動游標。

實例一:直接操作 SQLiteDatabase

版面檔 main.xml:

<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"
    tools:context=".Main">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="key" />

        <EditText
            android:id="@+id/keys"
            android:layout_width="100sp"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="value" />

        <EditText
            android:id="@+id/values"
            android:layout_width="100sp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn"
            android:layout_width="100sp"
            android:layout_height="wrap_content"
            android:text="submit" />
    </LinearLayout>

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

清單列項目 mytextview.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/listkey"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left" />

    <TextView
        android:id="@+id/listvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="300sp" />
</LinearLayout>

Main.java:

package com.app.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class Main extends Activity {

    EditText ed1, ed2;
    Button btn;
    ListView lv;
    SQLiteDatabase db;

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

        ed1 = (EditText) this.findViewById(R.id.keys);
        ed2 = (EditText) this.findViewById(R.id.values);
        btn = (Button) this.findViewById(R.id.btn);
        lv = (ListView) this.findViewById(R.id.lv);

        db = SQLiteDatabase.openOrCreateDatabase(
                this.getFilesDir().toString() + "/my.db3", null);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                String key = ed1.getText().toString();
                String value = ed2.getText().toString();
                try {
                    insertData(db, key, value);
                    Cursor cursor = db.rawQuery("select * from tb_info", null);
                    inflateListView(cursor);
                } catch (Exception e) {
                    // 表不存在時建立它,再重試一次
                    String sql = "create table tb_info(_id integer primary key "
                            + "autoincrement, db_key varchar(20), db_value varchar(50))";
                    db.execSQL(sql);
                    insertData(db, key, value);
                    Cursor cursor = db.rawQuery("select * from tb_info", null);
                    inflateListView(cursor);
                }
            }
        });
    }

    private void insertData(SQLiteDatabase db, String key, String value) {
        db.execSQL("insert into tb_info values (null,?,?)",
                new String[]{key, value});
    }

    @SuppressLint("NewApi")
    public void inflateListView(Cursor cursor) {
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(
                Main.this, R.layout.mytextview, cursor,
                new String[]{"db_key", "db_value"},
                new int[]{R.id.listkey, R.id.listvalue},
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        lv.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (db != null && db.isOpen()) {
            db.close();
        }
    }
}

這裡有個硬性要求:使用 SimpleCursorAdapter 時,底層資料表的主鍵欄位名稱必須是 _id,因為它只認得這個名字。範例刻意用 try/catch 包住每一次操作,是為了示範「表不存在就先建表」;正式專案不該這樣寫,理由見下節。

進階:改用 SQLiteOpenHelper

openOrCreateDatabase() 的缺點很明顯:每個 CRUD 方法都得包 try/catch,一旦表不存在就要在 catch 裡重建再重試,重複程式碼多到難以維護。實務上一致改用 SQLiteOpenHelper。

主要方法:

  • getReadableDatabase()/getWritableDatabase():取得可讀/可寫的資料庫物件。
  • onCreate(SQLiteDatabase db):資料庫首次建立時回呼,通常用來建表。
  • onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):版本升級時回呼。
  • close():關閉所有已開啟的資料庫。

使用步驟:繼承 SQLiteOpenHelper(建構子的 name 參數即資料庫名稱),並覆寫 onCreate 與 onUpgrade。

package com.app.db;

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

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

    String createSQL = "create table tb_test(_id integer primary key "
            + "autoincrement, name, age)";

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

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

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 依需求做 ALTER TABLE 或 DROP + 重建
    }
}
package com.app.main;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;

import com.app.db.MySQLiteOpenHelper;

public class Main extends Activity {

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

        MySQLiteOpenHelper helper =
                new MySQLiteOpenHelper(this, "my.db3", null, 1);

        SQLiteDatabase db = helper.getReadableDatabase();
        db.execSQL("insert into tb_test values(null,'wx',18)");

        Cursor cursor = db.rawQuery("select * from tb_test", null);
        if (cursor.moveToFirst()) {
            int id = cursor.getInt(0);
            Toast.makeText(this, id + "", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }
}

三個實務提醒

其一,Cursor 用完要關。CursorAdapter 管理的 Cursor 由 Adapter 負責,但自己用 rawQuery 建立的必須自行 close(),否則會觸發 finalizer 的 leak 警告。

其二,getReadableDatabase() 在磁碟空間不足或需要寫入時會實際開啟可寫資料庫,因此「唯讀情境」請勿假定它絕不寫檔;建表邏輯一律放在 onCreate。

其三,寫入操作盡量包在 beginTransaction()/setTransactionSuccessful()/endTransaction() 之間。批次插入包在交易裡,效能通常能有一到兩個數量級的差距。

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