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

Android SQLite 資料庫入門:從建表到增刪改查的完整流程

編輯:關於 Android 程式設計

App 的核心價值往往取決於怎麼處理資料,而 Android 內建的 SQLite 正是最輕量、最直接的選擇——不需另外安裝服務,整個資料庫就是一個檔案。本文從「把結構定義集中管理」這個好習慣開始,逐步完成建表、插入、更新、刪除與查詢,並示範如何用 adb 實際走進資料庫驗證結果。

先想清楚:為什麼要獨立一個常數類?

很多人把表名、欄位名散落在各處寫死,結果要改欄位時得全專案搜尋。更好的做法是集中在一個類別裡,日後要升級結構只改一處。

DatabaseStatic.java

 package com.example.databaseHelper;

 public class DatabaseStatic {
     public final static String DATABASE_NAME = "BookStore.db";
     public final static int DATABASE_VERSION = 1;
     public final static String TABLE_NAME = "book";
     public final static String BOOK_NAME = "bookName";
     public final static String ID = "_id";
     public final static String AUTHOR = "author";
     public final static String PRICE = "price";
 } 

MyHelper.java:繼承 SQLiteOpenHelper

 package com.example.databaseHelper;

 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteDatabase.CursorFactory;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.util.Log;
 import android.widget.Toast;

 /**
 * 繼承 SQLiteOpenHelper 並覆寫 onCreate 與 onUpgrade。
 * onCreate 會在資料庫檔案不存在時被呼叫,用來建立新的資料庫。
 */
 public class MyHelper extends SQLiteOpenHelper {

     // 建表 SQL:_id 設為主鍵並自動編號
     public static String CREATE_TABLE = "create table " + DatabaseStatic.TABLE_NAME + "("
             + DatabaseStatic.BOOK_NAME + " varchar(30), "
             + DatabaseStatic.ID + " Integer primary key autoincrement, "
             + DatabaseStatic.AUTHOR + " varchar(20) not null, "
             + DatabaseStatic.PRICE + " real)";

     private Context myContext = null;

     public MyHelper(Context context) {
         super(context, DatabaseStatic.DATABASE_NAME, null, DatabaseStatic.DATABASE_VERSION);
         myContext = context;
     }

     @Override
     public void onCreate(SQLiteDatabase db) {
         Log.i("UseDatabase", "建立資料庫");
         Toast.makeText(myContext, "建立資料庫", Toast.LENGTH_SHORT).show();
         db.execSQL(CREATE_TABLE);
     }

     @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         // 正式專案請在這裡實作版本升級邏輯
     }
 } 

onCreate 的觸發時機很關鍵:當你呼叫 getWritableDatabase() 或 getReadableDatabase() 時,若資料庫檔案不存在,才會回頭執行 onCreate 建立檔案與表格;檔案已存在則完全不會觸發。這也是為什麼「資料庫不存在」和「表不存在」是兩件不同的事——檔案存在但表沒建,onCreate 不會幫你補救。

版面配置:五個按鈕對應五種操作

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:id="@+id/mainLayout"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical"
     android:gravity="center_horizontal">

     <Button android:id="@+id/buttonCreateDatabase"
         android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:text="建立資料庫" />
     <Button android:id="@+id/buttonInsertDatabase"
         android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:text="插入資料" />
     <Button android:id="@+id/buttonUpdateDatabase"
         android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:text="更新資料" />
     <Button android:id="@+id/buttonDeleteDatabase"
         android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:text="刪除資料" />
     <Button android:id="@+id/buttonQueryDatabase"
         android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:text="顯示 Book 表中的所有資料" />
</LinearLayout> 

MainActivity:五種操作的實作

 public class MainActivity extends Activity {

     private MyHelper myHelper = null;
     private SQLiteDatabase database = null;
     private static int bookSum = 0;
     private TextView textView = null;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         textView = new TextView(this);
         LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
         layout.addView(textView);

         findViewById(R.id.buttonCreateDatabase).setOnClickListener(listener);
         findViewById(R.id.buttonInsertDatabase).setOnClickListener(listener);
         findViewById(R.id.buttonUpdateDatabase).setOnClickListener(listener);
         findViewById(R.id.buttonDeleteDatabase).setOnClickListener(listener);
         findViewById(R.id.buttonQueryDatabase).setOnClickListener(listener);
     }

     private View.OnClickListener listener = new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             switch (v.getId()) {
                 case R.id.buttonCreateDatabase: createDatabase(); break;
                 case R.id.buttonInsertDatabase: insertDatabase(); break;
                 case R.id.buttonUpdateDatabase: updateDatabase(); break;
                 case R.id.buttonDeleteDatabase: deleteDatabase(); break;
                 case R.id.buttonQueryDatabase: searchDatabase(); break;
             }
         }
     };

     /** 建立或開啟資料庫 */
     private void createDatabase() {
         myHelper = new MyHelper(this);
         // 檔案不存在時,會回呼 MyHelper.onCreate 建立檔案與 book 表
         myHelper.getWritableDatabase();
     }

     /** 插入一筆資料。ContentValues 的作用近似於 key-value 的 HashMap */
     private void insertDatabase() {
         if (myHelper == null) myHelper = new MyHelper(this);
         database = myHelper.getWritableDatabase();
         ContentValues cV = new ContentValues();
         cV.put(DatabaseStatic.BOOK_NAME, "C Language");
         cV.put(DatabaseStatic.ID, ++bookSum);
         cV.put(DatabaseStatic.AUTHOR, "zhidian");
         cV.put(DatabaseStatic.PRICE, 42.6);
         database.insert(DatabaseStatic.TABLE_NAME, null, cV);
         // 等效 SQL:
         // insert into book(bookName, _id, author, price) values(?, ?, ?, ?)
         Toast.makeText(this, "插入資料成功", Toast.LENGTH_SHORT).show();
     }

     /** 更新資料:把書名為 C Language 的作者改為 xiaoming */
     private void updateDatabase() {
         if (myHelper == null) myHelper = new MyHelper(this);
         database = myHelper.getWritableDatabase();
         ContentValues cV = new ContentValues();
         cV.put(DatabaseStatic.AUTHOR, "xiaoming");
         database.update(DatabaseStatic.TABLE_NAME, cV,
                 DatabaseStatic.BOOK_NAME + "= ?", new String[]{"C Language"});
         Toast.makeText(this, "資料更新成功", Toast.LENGTH_SHORT).show();
     }

     /** 刪除資料 */
     private void deleteDatabase() {
         if (myHelper == null) myHelper = new MyHelper(this);
         database = myHelper.getWritableDatabase();
         database.delete(DatabaseStatic.TABLE_NAME,
                 DatabaseStatic.BOOK_NAME + " = ? ", new String[]{"C Language"});
         Toast.makeText(this, "資料刪除成功", Toast.LENGTH_SHORT).show();
     }

     /** 查詢並顯示全部資料 */
     private void searchDatabase() {
         if (myHelper == null) myHelper = new MyHelper(this);
         database = myHelper.getWritableDatabase();
         // 各參數皆為 null 代表不加任何條件,等同 select * from book
         Cursor cursor = database.query(DatabaseStatic.TABLE_NAME, null, null, null, null, null, null);
         StringBuilder str = new StringBuilder();
         if (cursor.moveToFirst()) {
             for (; !cursor.isAfterLast(); cursor.moveToNext()) {
                 str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.ID)) + " ");
                 str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.BOOK_NAME)) + " ");
                 str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.AUTHOR)) + " ");
                 str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.PRICE)) + "\n");
             }
         }
         cursor.close(); // Cursor 用完務必關閉
         if (str.toString().equals("")) {
             str.append("資料庫為空!");
             textView.setTextColor(Color.RED);
         } else {
             textView.setTextColor(Color.BLACK);
         }
         textView.setText(str.toString());
     }
 } 

用 adb 驗證:確認資料真的進去了

程式邏輯寫完,總要親眼確認資料庫內容。Android 的資料庫檔案存放在 /data/data/<包名>/databases/:

開啟 cmd,執行 adb shell,接著 cd /data/data/com.example.UseDataBase/databases 進入目錄,再用 ls 確認檔案存在:

輸入 sqlite3 BookStore.db 進入 SQLite 命令列,再用 .tables 列出所有表:

你會看到 book 表确实被建立了,另外還有一個 android_metadata——這是每個資料庫都會自動產生、用來記錄區域設定的系統表,不需要理它。

回到 App 按下「插入資料」,然後在 sqlite 提示符號下執行查詢:

 select * from book; 

接著測試更新:

再測試刪除,用 select * from book; 查詢已無任何資料:

最後按下 App 上的查詢按鈕,畫面會顯示「資料庫為空!」:

SQLite 常用資料類型

整數 Integer、字串 varchar(10)、浮點數 real、文字 text。SQLite 採用動態型別,實際上比這寬鬆得多,但建表時仍建議標明型別以便閱讀。

常用 SQL 語句速查

1. 建表

 create table 表名(欄位1 型別 約束條件, 欄位2 型別 約束條件...) 

例:

 create table person(_id Integer primary key autoincrement, name varchar(20),
                     sex varchar(5) not null, age Integer) 

2. 插入

 insert into 表名(欄位1, 欄位2...) values(值1, 值2...)
 insert into 表名 values(值1, 值2...) 

例:

 insert into person(_id, name, sex, age) values(1, '指點', '男', 19) 

3. 更新

 update 表名 set 欄位1 = 值, 欄位2 = 值... where 條件1 and 條件2 or 條件3... 

where 子句中的條件可用 and / or 串接。例:

 update person set _id = 0, age = 18 where _id = 1 and age <> 19 

4. 刪除

 delete from 表名 where 條件1 and 條件2 or 條件3... 

例:

 delete from person where _id > 0 and name = '指點' 

以上四種操作都可用 execSQL() 帶入參數執行。

5. 查詢

 select 欄位1, 欄位2... from 表名 where 條件1 and 條件2... 

例:

 select _id, name, sex from person where name = '指點' or _id = 1 

查詢必須用 rawQuery() 或 query() 執行,回傳 Cursor 物件。

幾個務實提醒

用參數,不要用字串拼接。 上面範例中的 ? 佔位符不只是好看——它同時解決了 SQL Injection 風險與引號跳脫問題,養成習慣很重要。

記得關閉 Cursor 與 Database。 長期累積未關閉的游標會觸發 SQLiteCursorLeak 警告,最終導致記憶體不足。

不要在主執行緒做資料庫操作。 大量寫入會造成畫面卡頓甚至 ANR,正式專案應改用 Room 搭配 Coroutines,或至少放到背景執行緒。

結構升級要實作 onUpgrade。 範例中的 onUpgrade 是空的,這代表一旦版本號提高,舊使用者的資料表不會有任何變化,反而可能出錯。正式上線前務必依版本差異寫好 ALTER TABLE 或重建邏輯。

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