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

Android SQLite 資料庫操作實作

編輯:關於 Android 程式設計

Android 操作 SQLite 通常會建立 SQLiteOpenHelper 子類,負責建立與升級資料庫。實際新增、修改、查詢則透過 SQLiteDatabase 完成。

建立 Helper

public class Sqlite extends SQLiteOpenHelper {
    public Sqlite(Context context, String name, int version) {
        super(context, name, null, version);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table user(id int, name varchar(20))");
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 依需求處理表格變更
    }
}

新增與查詢

Sqlite helper = new Sqlite(this, "test.db", 1);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", 1);
values.put("name", "zhangsan");
db.insert("user", null, values);

Cursor cursor = db.query("user", new String[]{"id", "name"},
    "id=?", new String[]{"1"}, null, null, null);
while (cursor.moveToNext()) {
    String name = cursor.getString(cursor.getColumnIndex("name"));
}
cursor.close();

更新資料可使用 db.update,並以 where 子句指定列。操作完成後應妥善關閉 Cursor 與資料庫連線,避免資源浪費。

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