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

跟著學 Android 之十三:SQLite 資料庫操作全攻略

編輯:關於 Android 程式設計

本章內容

第 1 節 SQLite 資料庫概述

第 2 節 SQLite 建庫建表

第 3 節 管理資料庫連線

第 4 節 操作資料庫資料

第 5 節 資料綁定

本章目標

掌握 SQLite 資料的基本特點與工具使用。

熟練掌握 SQLite 建庫建表的方法。

熟練掌握連接 SQLite 資料庫的方法。

熟悉 SQLite 資料庫的升級與建立方法。

掌握透過資料綁定完成資料顯示的方法。

SQLite 是一款極為流行的嵌入式資料庫,以 C 語言編寫而成,屬於輕量級關聯式資料庫。它支援標準 SQL、可跨越多種作業系統、完全獨立運行且沒有外部依賴,而 Android 系統本身就內嵌了 SQLite。

要操作資料庫檔案,官方提供了命令列工具,可從官網下載:

https://www.sqlite.org/download.html

下載 sqlite-shell-******.zip 後解壓縮,即可得到 sqlite3 執行檔,將其所在路徑加入 PATH 環境變數即可使用。連接資料庫檔案的方式如下:

$ sqlite3<資料庫檔案路徑>

sqlite3 工具的所有管理命令皆以「.」開頭,在命令列下也可直接輸入標準 SQL 語句。除了官方的 sqlite3 之外,還有許多非官方的圖像化管理工具,例如:

SQLite Database Browser

SQLite Expert Professional

SQLite Develope

SQLite 與大型資料庫的差異

兩者同為關聯式資料庫,但 SQLite 是嵌入型的輕量級資料庫,適合小資料量情境;大型資料庫則獨立運行於資料庫伺服器上,適合大資料量,且通常以網路方式對外提供服務。

建立 SQLite 資料庫

$ sqlite3 test.db

在命令列輸入上述指令後,若 test.db 不存在則會預先建立(直到執行相關 SQL 才會真正產生檔案);若已存在,則直接連接該資料庫。

$ sqlite3 test.db <sql.script>

這條指令能在建立資料庫的同時,利用 sql.script 進行初始化。

SQLite 的資料類型

SQLite 的欄位可以儲存任意類型的資料,但為了與其他資料庫相容,仍可為欄位指定預設類型:

NULL:空值

INTEGER:帶正負號的整數,實際大小取決於存入數字的範圍

REAL:浮點數,以 8 bytes 儲存

TEXT:字串文字

BLOB:二進位物件

此外亦接受 smallint、int、float、double 等型別,以及 char(n)、varchar(n)、date、time、timestamp 等相容寫法。

建立 SQLite 資料表(透過 SQL 語句):

 create table books ( id integer primary key autoincrement, name varchar(128) not null unique, author varchar(128) not null, price double not null ); 

建立表間關聯(透過外鍵建立關係):

 create table groups( id integer primary key autoincrement, name varchar(128) not null unique ); create table users( id integer primary key autoincrement, group_id integer constraint fk_users_group_id references groups(id), username varchar(128) not null, password varchar(128) not null ); 

事務控制

SQLite 支援資料庫事務:

 sqlite> begin; sqlite> insert into ...... sqlite> commit; sqlite> rollback; 

Android 系統中 SQLite 資料庫檔案的儲存位置

預設情況下,資料庫檔案存放在:

/data/data/<應用程式包>/databases

使用者也可指定存放於任何有權限的目錄(例如 SD 卡)。在 Android 中,可使用 SQLiteDatabase 類別連接資料庫:

 SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); 

透過 SQLiteOpenHelper 類別連接資料庫:

 public class MyHelper extends SQLiteOpenHelper { public static final int VERSION = 1; public static final String DATABASE_NAME = "test.db"; public MyHelper(Context context) { super(context, DATABASE_NAME, null, VERSION); } } SQLiteDatabase db = helper.getWritableDatabase(); 

資料庫升級與存在性檢測

當應用程式升級時,需要檢測資料庫是否存在、是否需要升級。SQLiteOpenHelper 已提供建立與升級的能力,覆寫 onCreate 完成建立任務:

 public void onCreate(SQLiteDatabase db) { String str_sql = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TEXT + " text);"; db.execSQL(str_sql); } 

覆寫 onUpgrade 完成升級任務:

 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 在此填寫資料庫升級操作的程式碼 } 

合理關閉資料庫連線

在不再使用、長時間不用、程式退出或暫停時,都應呼叫 SQLiteDatabase 的 close 方法關閉連線。

執行操作(假設已取得連線句柄 db)

SQLiteDatabase 提供了豐富的方法:execSQL、insert/insertOrThrow/insertWithOnConflict、query/rawQuery、replace/replaceOrThrow、update/updateWithOnConflict、delete 等。

插入記錄示例:

 ContentValues cv = new ContentValues(); cv.put("name",user.getName()); cv.put("age",user.getAge()); cv.put("remark",user.getRemark()); db.insert("users",null, cv);

刪除記錄示例:

 // 第一個參數為表名 // 第二個參數為 where 後的條件表達式,可使用 ? // 第三個參數為對應每個 ? 的值陣列 db.delete("users", "id=?", new String[]{String.valueOf(userId)}); 

更新記錄示例:

 ContentValues cv = new ContentValues(); cv.put("name", user.getName()); cv.put("age", user.getAge()); cv.put("remark", user.getRemark()); db.update("users", cv, "id=?", new String[]{String.valueOf(userId)}); 

單表查詢所有記錄示例:

 Cursor c = db.query("users", null, null, null, null, null, "name"); List users = null; if(c != null) { users = new ArrayList(); while(c!=null && c.moveToNext()) { User u = new User(); u.setId(c.getInt(0)); u.setName(c.getString(1)); u.setAge(c.getInt(2)); u.setRemark(c.getString(3)); users.add(u); } c.close(); } 

單表條件查詢示例:

 Cursor c = db.query( "users", new String[]{"name", "age"}, "age > ?", new String[]{"10"}, null, null, "name desc" ); 

事務是確保資料庫操作原子性的保障,SQLiteDatabase 提供 beginTransaction(開啟)、setTransactionSuccessful(提交)、endTransaction(關閉,未提交則自動 rollback):

 db.beginTransaction(); try { ...... db.setTransactionSuccessful(); } finally { db.endTransaction(); } 

資料綁定的必要性

資料綁定是指將介面與資料進行綁定,有助於資料的呈現。Adapter 就是介面與資料之間的橋樑,能降低維護資料的複雜度。SimpleCursorAdapter 則提供了資料層到清單的綁定能力。

1. 準備一個清單項的版面配置供 ListView 使用:

    

2. 使用 SimpleCursorAdapter 呈現資料:

 ListView bookListView = (ListView)findViewById(R.id.booklist); String [] from = new String[] { "_name", "_age" }; int [] to = new int[] { R.id.nametextview, R.id.agetextview }; Cursor cursor = db.rawQuery("select * from books", null); SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, R.layout.book_list_item, cursor, from, to, 0); bookListView.setAdapter(adapter); 

修改綁定資料

若直接呈現的資料不符合要求,可透過 SimpleCursorAdapter.ViewBinder 介面進行轉換。步驟如下:

1. 撰寫一個類別實作 ViewBinder 介面:

 SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() { public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if(cursor.getColumnIndex("_name") == columnIndex) { TextView v = (TextView)view; v.setText("N:" + cursor.getString(columnIndex)); return true; } return false; } }; 

2. 使用 ViewBinder 修改資料:

 ListView bookListView = (ListView)findViewById(R.id.booklist); String [] from = new String[] { "_name", "_age" }; int [] to = new int[] { R.id.nametextview, R.id.agetextview }; Cursor cursor = db.rawQuery("select * from books", null); SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, R.layout.book_list_item, cursor, from, to, 0); adapter.setViewBinder(viewBinder); bookListView.setAdapter(adapter); 
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved