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

Android學習指南之十五:深入SQLite數據庫與增刪改查實戰

編輯:關於 Android 開發

在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,以及相應的文本提示。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android">
  3. <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>
  4. <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>
  5. <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>
  6. <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>
  7. <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>
  8. <spinner android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margintop="5dp" android:id="@+id/Spinner01" android:minwidth="200dp"></spinner>
  9. <textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/TextView02"></textview>
  10. </linearlayout>

第三步,在MainHelloSqlite.java同目錄下新建一個數據庫操作輔助類DbHelper.java,它繼承自SQLiteOpenHelper,負責數據庫的創建與版本管理。

  1. package android.basic.lesson15;
  2. import android.content.Context;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.database.sqlite.SQLiteDatabase.CursorFactory;
  5. import android.database.sqlite.SQLiteOpenHelper;
  6. public class DbHelper extends SQLiteOpenHelper {
  7.     public DbHelper(Context context, String name, CursorFactory factory, int version) {
  8.         super(context, name, factory, version);
  9.     }
  10.     //輔助類創建時會執行該方法,用於建表
  11.     @Override
  12.     public void onCreate(SQLiteDatabase db) {
  13.         String sql = "CREATE TABLE pic (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fileName VARCHAR, description VARCHAR)";
  14.         db.execSQL(sql);
  15.     }
  16.     @Override
  17.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  18.     }
  19. }

第四步,編寫MainHelloSqlite.java。這裡我們直接使用SQLiteDatabase封裝好的insert、delete、update、query方法來完成四種基本操作,並把結果實時反映到下拉列表中。

  1. package android.basic.lesson15;
  2. import android.app.Activity;
  3. import android.content.ContentValues;
  4. import android.database.Cursor;
  5. import android.database.sqlite.SQLiteDatabase;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.view.View.OnClickListener;
  9. import android.widget.AdapterView;
  10. import android.widget.AdapterView.OnItemSelectedListener;
  11. import android.widget.Button;
  12. import android.widget.SimpleCursorAdapter;
  13. import android.widget.Spinner;
  14. import android.widget.TextView;
  15. import android.widget.Toast;
  16. public class MainHelloSqlite extends Activity {
  17.     SQLiteDatabase db;
  18.     public String db_name = "gallery.sqlite";
  19.     public String table_name = "pic";
  20.     final DbHelper helper = new DbHelper(this, db_name, null, 1);
  21.     @Override
  22.     public void onCreate(Bundle savedInstanceState) {
  23.         super.onCreate(savedInstanceState);
  24.         setContentView(R.layout.main);
  25.         Button b1 = (Button) findViewById(R.id.Button01);
  26.         Button b2 = (Button) findViewById(R.id.Button02);
  27.         Button b3 = (Button) findViewById(R.id.Button03);
  28.         Button b4 = (Button) findViewById(R.id.Button04);
  29.         //從輔助類獲得可寫數據庫對象
  30.         db = helper.getWritableDatabase();
  31.         initDatabase(db);
  32.         updateSpinner();
  33.         OnClickListener ocl = new OnClickListener() {
  34.             @Override
  35.             public void onClick(View v) {
  36.                 ContentValues cv = new ContentValues();
  37.                 switch (v.getId()) {
  38.                     //添加:成功返回行號,失敗返回-1
  39.                     case R.id.Button01:
  40.                         cv.put("fileName", "pic5.jpg");
  41.                         cv.put("description", "圖片5");
  42.                         long long1 = db.insert("pic", "", cv);
  43.                         Toast.makeText(MainHelloSqlite.this, "ID是" + long1 + "的圖片操作完成", Toast.LENGTH_SHORT).show();
  44.                         updateSpinner();
  45.                         break;
  46.                     //刪除:失敗返回0,成功返回刪除條數
  47.                     case R.id.Button02:
  48.                         long long2 = db.delete("pic", "description='圖片5'", null);
  49.                         Toast.makeText(MainHelloSqlite.this, "刪除了" + long2 + "條記錄", Toast.LENGTH_SHORT).show();
  50.                         updateSpinner();
  51.                         break;
  52.                     //更新:失敗返回0,成功返回更新條數
  53.                     case R.id.Button03:
  54.                         cv.put("fileName", "pic0.jpg");
  55.                         cv.put("description", "圖片0");
  56.                         int long3 = db.update("pic", cv, "fileName='pic5.jpg'", null);
  57.                         Toast.makeText(MainHelloSqlite.this, "更新了" + long3 + "條記錄", Toast.LENGTH_SHORT).show();
  58.                         updateSpinner();
  59.                         break;
  60.                     //查詢:遍歷游標並逐條顯示
  61.                     case R.id.Button04:
  62.                         Cursor c = db.query("pic", null, null, null, null, null, null);
  63.                         Toast.makeText(MainHelloSqlite.this, "當前共有" + c.getCount() + "條記錄", Toast.LENGTH_SHORT).show();
  64.                         for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
  65.                             Toast.makeText(MainHelloSqlite.this, "第"+ c.getInt(0) +"條,文件名" + c.getString(1) + ",描述"+c.getString(2), Toast.LENGTH_SHORT).show();
  66.                         }
  67.                         updateSpinner();
  68.                         break;
  69.                 }
  70.             }
  71.         };
  72.         b1.setOnClickListener(ocl);
  73.         b2.setOnClickListener(ocl);
  74.         b3.setOnClickListener(ocl);
  75.         b4.setOnClickListener(ocl);
  76.     }
  77.     //初始化表數據
  78.     public void initDatabase(SQLiteDatabase db) {
  79.         ContentValues cv = new ContentValues();
  80.         cv.put("fileName", "pic1.jpg"); cv.put("description", "圖片1"); db.insert(table_name, "", cv);
  81.         cv.put("fileName", "pic2.jpg"); cv.put("description", "圖片2"); db.insert(table_name, "", cv);
  82.         cv.put("fileName", "pic3.jpg"); cv.put("description", "圖片3"); db.insert(table_name, "", cv);
  83.         cv.put("fileName", "pic4.jpg"); cv.put("description", "圖片4"); db.insert(table_name, "", cv);
  84.     }
  85.     //刷新下拉列表:用SimpleCursorAdapter把游標綁定到Spinner
  86.     public void updateSpinner() {
  87.         final TextView tv = (TextView) findViewById(R.id.TextView02);
  88.         Spinner s = (Spinner) findViewById(R.id.Spinner01);
  89.         final Cursor cursor = db.query("pic", null, null, null, null, null, null);
  90.         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});
  91.         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  92.         s.setAdapter(adapter);
  93.         OnItemSelectedListener oisl = new OnItemSelectedListener() {
  94.             @Override
  95.             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
  96.                 cursor.moveToPosition(position);
  97.                 tv.setText("當前pic的描述為:" + cursor.getString(2));
  98.             }
  99.             @Override
  100.             public void onNothingSelected(AdapterView<?> parent) {
  101.             }
  102.         };
  103.         s.setOnItemSelectedListener(oisl);
  104.     }
  105.     @Override
  106.     public void onDestroy() {
  107.         super.onDestroy();
  108.         db.delete(table_name, null, null);
  109.         updateSpinner();
  110.     }
  111. }

第五步,運行程序查看效果:

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

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