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

Android 中使用 SQLite 資料庫:建立、增刪改查與交易處理

編輯:Android 開發教學

專案原始碼下載

https://github.com/Wang-Jun-Chao/AndroidProjects

SQLite 簡介

SQLite 是一個輕量級的關聯式資料庫,內建於 Android 系統中。建立資料庫時使用的核心 API 是 SQLiteOpenHelper,開發者需要自訂一個子類並覆寫相關回呼方法。

首先必須定義一個建構子:

// arg1:資料庫檔案名稱
// arg2:游標工廠
// arg3:資料庫版本
public MyOpenHelper(Context context, String name,
                    CursorFactory factory, int version) {
    super(context, name, factory, version);
}

兩個關鍵回呼:資料庫首次被建立時會呼叫 onCreate();資料庫版本升級時會呼叫 onUpgrade()。

建立資料庫

MyOpenHelper oh = new MyOpenHelper(getContext(), "person.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();

兩個取得資料庫的方法有細微差別:

getWritableDatabase():開啟可讀寫的資料庫。

getReadableDatabase():磁碟空間不足時會開啟唯讀資料庫,否則開啟可讀寫資料庫。

建表動作通常寫在 onCreate() 中:

public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table person (_id integer primary key autoincrement, "
            + "name varchar(20), phone varchar(20), money int)");
}

資料庫的增刪改查

方式一:直接執行 SQL 語句

// 插入
db.execSQL("insert into person (name, phone, money) values (?, ?, ?)",
        new Object[]{"tom", "110", 100});

// 刪除
db.execSQL("delete from person where name = ?", new Object[]{"_id = 1"});

// 修改
db.execSQL("update person set money = ? where name = ?",
        new Object[]{200, "tom"});

// 查詢
Cursor cs = db.rawQuery("select name, phone from person where name = ?",
        new String[]{"tom"});

若使用 JUnit 測試,可在測試方法執行前先透過 setUp() 完成初始化:

@Before
public void setUp() throws Exception {
    oh = new MyOpenHelper(getContext(), "person.db", null, 1);
}

方式二:使用 API 方法

插入

ContentValues cv = new ContentValues();
cv.put("name", "tom");
cv.put("phone", "110");
cv.put("money", 100);
long i = db.insert("person", null, cv);

刪除

int i = db.delete("person", "name = ?", new String[]{"tom"});

修改

ContentValues cv = new ContentValues();
cv.put("money", 200);
int i = db.update("person", cv, "name = ?", new String[]{"tom"});

查詢

Cursor cs = db.query("person", new String[]{"name", "money"},
        null, null, null, null, null);

while (cs.moveToNext()) {
    String name = cs.getString(cs.getColumnIndex("name"));
    String money = cs.getString(cs.getColumnIndex("money"));
    System.out.println(name + " " + money);
}

兩種方式相比:SQL 語句更直接、彈性更高;API 方法則能避免拼接字串的風險,也不容易打錯欄位名。

交易(Transaction)

交易用來保證多條 SQL 語句要嘛全部成功,要嘛全部失敗。最常見的場景就是銀行轉帳——扣款與入帳必須是不可分割的一體。

try {
    db.beginTransaction();
    // 執行多條更新語句
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}

這裡有個容易忽略的細節:setTransactionSuccessful() 必須在 endTransaction() 之前呼叫,否則交易會被回滾。

把資料庫資料顯示到畫面

先任意插入幾筆資料,接著定義業務用的 bean 類別 Person.java,然後把資料讀出來裝進集合:

Cursor cs = db.query("person", null, null, null, null, null, null);

List<Person> people = new ArrayList<Person>();

while (cs.moveToNext()) {
    String name = cs.getString(cs.getColumnIndex("name"));
    String phone = cs.getString(cs.getColumnIndex("phone"));
    String money = cs.getString(cs.getColumnIndex("money"));

    Person p = new Person(name, phone, money);
    people.add(p);
}

再把集合中的資料逐筆加進版面容器:

LinearLayout ll = (LinearLayout) findViewById(R.id.ll);

for (Person p : people) {
    TextView tv = new TextView(this);
    tv.setText(p.toString());
    ll.addView(tv);
}

分頁查詢

資料量大時必須分頁,做法是在 query 的最後兩個參數填入 offset 與 limit:

Cursor cs = db.query("person", null, null, null, null, null, "_id asc", "0, 20");
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved