在Android開發中,數據的持久化存儲是繞不開的話題,而SQLite正是官方內置並推薦使用的解決方案。它無需額外配置、體積小巧,卻能勝任大多數本地數據存儲場景。本篇就帶大家全面認識SQLite,並通過一個完整的增刪改查範例,把理論落到實處。
一、SQLite是什麼
SQLite是一款開源、輕量級且內嵌式的關聯式數據庫,由D. Richard Hipp於2000年發布。幾乎所有主流編程語言——Java、.NET、PHP、Ruby、Python、Perl、C等——都能與之配合,運行平台也覆蓋了Windows、Linux、Unix、Mac OS、Android、iOS等常見系統。
其實SQLite早已潛藏在你的日常生活中。蘋果、Adobe、Google的眾多產品都在用它。打開迅雷或金山詞霸的安裝目錄,你會發現sqlite3.dll或sqlite.dll的身影。而在Android平台上,SQLite更是官方給出的標準數據庫選擇,並提供了完整的原生支持。
SQLite的主要特性:
1. 支持ACID事務
2. 零配置,無需安裝與維護
3. 整個數據庫保存在單個磁盤文件中
4. 數據庫文件可在不同字節序的機器間自由共享
5. 支持的最大數據庫可達2TB
6. 體積極小,約3萬行C代碼,僅250K左右
7. 在多數常規數據庫操作上比一些流行數據庫更快
8. API簡潔易用
9. 內置TCL綁定,並可通過Wrapper支持其他語言
10. 源碼註釋完善,測試覆蓋率超過90%
11. 獨立性強,沒有額外依賴
12. 源碼完全開放,可用於任何用途,包括商業銷售
13. 支援C、PHP、Perl、Java、ASP.NET、Python等多種語言
推薦一個好用的SQLite客戶端工具:火狐瀏覽器的Sqlite Manager插件。

二、Android中SQLite的實際應用
下面我們動手做一個範例,把關鍵講解都寫進代碼註釋裡,邊看邊學效果最好。
第一步,新建項目Lesson15_HelloSqlite,Activity命名為MainHelloSqlite.java。
第二步,編寫用戶界面res/layout/main.xml。界面需要放置增(insert)、刪(delete)、改(update)、查(select)四個按鈕,一個用於展示表數據的下拉列表Spinner,以及相應的文本提示。
- <?xml version="1.0" encoding="utf-8"?>
- <linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android">
- <textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/TextView01" android:text="SQLite基本操作"></textview>
- <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/Button01" android:text="增 | insert" android:minwidth="200dp"></button>
- <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/Button02" android:text="刪 | delete" android:minwidth="200dp"></button>
- <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/Button03" android:text="改 | update" android:minwidth="200dp"></button>
- <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/Button04" android:text="查 | select" android:minwidth="200dp"></button>
- <spinner android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margintop="5dp" android:id="@+id/Spinner01" android:minwidth="200dp"></spinner>
- <textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/TextView02"></textview>
- </linearlayout>
第三步,在MainHelloSqlite.java同目錄下新建一個數據庫操作輔助類DbHelper.java,它繼承自SQLiteOpenHelper,負責數據庫的創建與版本管理。
- package android.basic.lesson15;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DbHelper extends SQLiteOpenHelper {
- public DbHelper(Context context, String name, CursorFactory factory, int version) {
- super(context, name, factory, version);
- }
- //輔助類創建時會執行該方法,用於建表
- @Override
- public void onCreate(SQLiteDatabase db) {
- String sql = "CREATE TABLE pic (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fileName VARCHAR, description VARCHAR)";
- db.execSQL(sql);
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- }
- }
第四步,編寫MainHelloSqlite.java。這裡我們直接使用SQLiteDatabase封裝好的insert、delete、update、query方法來完成四種基本操作,並把結果實時反映到下拉列表中。
- package android.basic.lesson15;
- import android.app.Activity;
- import android.content.ContentValues;
- 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.AdapterView;
- import android.widget.AdapterView.OnItemSelectedListener;
- import android.widget.Button;
- import android.widget.SimpleCursorAdapter;
- import android.widget.Spinner;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainHelloSqlite extends Activity {
- SQLiteDatabase db;
- public String db_name = "gallery.sqlite";
- public String table_name = "pic";
- final DbHelper helper = new DbHelper(this, db_name, null, 1);
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button b1 = (Button) findViewById(R.id.Button01);
- Button b2 = (Button) findViewById(R.id.Button02);
- Button b3 = (Button) findViewById(R.id.Button03);
- Button b4 = (Button) findViewById(R.id.Button04);
- //從輔助類獲得可寫數據庫對象
- db = helper.getWritableDatabase();
- initDatabase(db);
- updateSpinner();
- OnClickListener ocl = new OnClickListener() {
- @Override
- public void onClick(View v) {
- ContentValues cv = new ContentValues();
- switch (v.getId()) {
- //添加:成功返回行號,失敗返回-1
- case R.id.Button01:
- cv.put("fileName", "pic5.jpg");
- cv.put("description", "圖片5");
- long long1 = db.insert("pic", "", cv);
- Toast.makeText(MainHelloSqlite.this, "ID是" + long1 + "的圖片操作完成", Toast.LENGTH_SHORT).show();
- updateSpinner();
- break;
- //刪除:失敗返回0,成功返回刪除條數
- case R.id.Button02:
- long long2 = db.delete("pic", "description='圖片5'", null);
- Toast.makeText(MainHelloSqlite.this, "刪除了" + long2 + "條記錄", Toast.LENGTH_SHORT).show();
- updateSpinner();
- break;
- //更新:失敗返回0,成功返回更新條數
- case R.id.Button03:
- cv.put("fileName", "pic0.jpg");
- cv.put("description", "圖片0");
- int long3 = db.update("pic", cv, "fileName='pic5.jpg'", null);
- Toast.makeText(MainHelloSqlite.this, "更新了" + long3 + "條記錄", Toast.LENGTH_SHORT).show();
- updateSpinner();
- break;
- //查詢:遍歷游標並逐條顯示
- case R.id.Button04:
- Cursor c = db.query("pic", null, null, null, null, null, null);
- Toast.makeText(MainHelloSqlite.this, "當前共有" + c.getCount() + "條記錄", Toast.LENGTH_SHORT).show();
- for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
- Toast.makeText(MainHelloSqlite.this, "第"+ c.getInt(0) +"條,文件名" + c.getString(1) + ",描述"+c.getString(2), Toast.LENGTH_SHORT).show();
- }
- updateSpinner();
- break;
- }
- }
- };
- b1.setOnClickListener(ocl);
- b2.setOnClickListener(ocl);
- b3.setOnClickListener(ocl);
- b4.setOnClickListener(ocl);
- }
- //初始化表數據
- public void initDatabase(SQLiteDatabase db) {
- ContentValues cv = new ContentValues();
- cv.put("fileName", "pic1.jpg"); cv.put("description", "圖片1"); db.insert(table_name, "", cv);
- cv.put("fileName", "pic2.jpg"); cv.put("description", "圖片2"); db.insert(table_name, "", cv);
- cv.put("fileName", "pic3.jpg"); cv.put("description", "圖片3"); db.insert(table_name, "", cv);
- cv.put("fileName", "pic4.jpg"); cv.put("description", "圖片4"); db.insert(table_name, "", cv);
- }
- //刷新下拉列表:用SimpleCursorAdapter把游標綁定到Spinner
- public void updateSpinner() {
- final TextView tv = (TextView) findViewById(R.id.TextView02);
- Spinner s = (Spinner) findViewById(R.id.Spinner01);
- final Cursor cursor = db.query("pic", null, null, null, null, null, null);
- SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] {"fileName", "description"}, new int[] {android.R.id.text1, android.R.id.text2});
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- s.setAdapter(adapter);
- OnItemSelectedListener oisl = new OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- cursor.moveToPosition(position);
- tv.setText("當前pic的描述為:" + cursor.getString(2));
- }
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- }
- };
- s.setOnItemSelectedListener(oisl);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- db.delete(table_name, null, null);
- updateSpinner();
- }
- }
第五步,運行程序查看效果:




本範例採用的是SQLiteDatabase已封裝好的insert、delete、update、query方法。有興趣的同學也可以嘗試用execSQL()和rawQuery()方法,直接執行原生SQL語句來實現同樣的功能。