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

Android SQLite 入門:從 adb shell 語法複習到增刪改查 API 實作

編輯:關於 Android 程式設計

開發過程中幾乎一定會碰到資料庫操作。Android 系統內建 SQLite,這是一款遵守 ACID 事特性的輕量級關聯式資料庫管理系統,佔用資源極低,能支援 Windows/Linux/Unix 等主流平台,也能與 C#、PHP、Java 等語言搭配。本文先透過 adb shell 複習 SQL 基本語法,再說明 Android 中的操作方式。

一、用 adb shell 複習 SQL 語句

ADB 是 Android SDK 自帶的除錯工具,位於 sdk 的 platform-tools 目錄下。透過 adb shell 可以進入裝置主控台,直接對資料庫下指令。

G:
cd G:\software\Program software\Android\adt-bundle-windows-x86_64-20140321\sdk\platform-tools
adb shell
cd /data/data/com.example.sqliteaction/databases/
sqlite3 StuDatabase.db
.table
.schema

先建立 SQLiteAction 專案,並在專案中建立 StuDatabase.db。輸入 adb shell 進入裝置主控台後,用「sqlite3 + 資料庫名」開啟資料庫,若指定的 db 檔不存在則會自動建立。

接著就能直接下 SQL 語法執行增刪改查。這裡特別提醒:SQL 語法很容易寫錯,漏掉一個右括號或結尾的分號,就會導致指令執行失敗。

-- 創建 Teacher 表
create table Teacher (id integer primary key, name text);
-- 向表中插入數據
insert into Teacher (id,name) values('10001', 'Mr Wang');
insert into Teacher (id,name) values('10002', 'Mr Yang');
-- 查詢數據
select * from Teacher;
-- 更新數據
update Teacher set name='Yang XZ' where id=10002;
-- 刪除數據
delete from Teacher where id=10001;

二、SQLite 資料庫操作 API

1. 建立與開啟資料庫
使用 openOrCreateDatabase(),它會自動判斷資料庫是否存在:存在就開啟,不存在就新建,並回傳一個 SQLiteDatabase 物件。

2. 建立資料表
把建表語法定義成字串,再用 execSQL() 執行。

// 創建學生表(學號,姓名,電話,身高) 主鍵學號
public static final String createTableStu = "create table Student (" +
        "id integer primary key, " +
        "name text, " +
        "tel text, " +
        "height real)";
// SQLiteDatabase 定義 db 變量
db.execSQL(createTableStu);

3. 插入資料
使用 insert()。ContentValues 本質上就是一個 Map,Key 是欄位名稱、Value 是對應的值。

SQLiteDatabase.insert(
    String table,            // 添加數據的表名
    String nullColumnHack,   // 為某些空的列自動復制 NULL
    ContentValues values     // ContentValues 的 put() 方法添加數據
);
// 方法一:ContentValues 方式
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", "10001");
values.put("name", "Eastmount");
values.put("tel", "15201610000");
values.put("height", "172.5");
db.insert("Student", null, values);

// 方法二:直接執行 SQL
public static final String insertData = "insert into Student (" +
        "id, name, tel, height) values('10002','XiaoMing','110','175')";
db.execSQL(insertData);

4. 刪除資料
使用 delete(),其中 sqlHelper 是繼承 SQLiteOpenHelper 自訂類別的實例。

SQLiteDatabase.delete(
    String table,        // 表名
    String whereClause,  // 約束刪除行,不指定則刪除所有行
    String[] whereArgs   // 對應數據
);
// 方法一:刪除身高 > 175cm
SQLiteDatabase db = sqlHelper.getWritableDatabase();
db.delete("Student", "height > ?", new String[] {"175"});

// 方法二
String deleteData = "DELETE FROM Student WHERE height>175";
db.execSQL(deleteData);

5. 更新資料
使用 update() 修改既有資料,SQL + execSQL() 的寫法就不重複贅述。

// 小明的身高修改為 180
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("height", "180");
db.update("Student", values, "name = ?", new String[] {"XiaoMing"});

6. 其他常用操作

// 關閉數據庫
SQLiteDatabase.close();
// 刪除表
SQLiteDatabase.execSQL("DROP TABLE Student");
// 刪除數據庫
this.deleteDatabase("StuDatabase.db");
// 查詢數據
SQLiteDatabase.query();

其中 query() 因為涉及 ListView 的資料綁定,放在下面的實例中一起說明。

三、完整實例

實作目標:一個包含學號、姓名、電話、身高四個欄位的學生表,畫面上方是標題列、中間是 ListView 資料列表、下方是輸入欄與「創表/插入/刪除/更新/查詢」五顆按鈕。

首先是 activity_main.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.touchimagetest.MainActivity"
    tools:ignore="MergeRootFrame" >

    <!-- 頂部 -->
    <RelativeLayout
        android:id="@+id/MyLayout_top"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:layout_alignParentTop="true" >

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center" >
            <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:layout_weight="1" android:gravity="center" android:textSize="20sp" android:text="學號" />
            <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:layout_weight="1" android:gravity="center" android:textSize="20sp" android:text="姓名" />
            <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:layout_weight="1" android:gravity="center" android:textSize="20sp" android:text="電話" />
            <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:layout_weight="1" android:gravity="center" android:textSize="20sp" android:text="身高" />
        </LinearLayout>
    </RelativeLayout>

    <!-- 底部按鈕 -->
    <RelativeLayout
        android:id="@+id/MyLayout_bottom"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="90dp"
        android:layout_alignParentBottom="true"
        android:gravity="center">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentBottom="true" >
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:gravity="center" >
                <EditText android:id="@+id/edit_id" android:layout_width="wrap_content" android:layout_height="wrap_content"
                    android:layout_weight="1" android:gravity="center" android:textSize="20sp" android:hint="學號" />
                <EditText android:id="@+id/edit_name" android:layout_width="wrap_content" android:layout_height="wrap_content"
                    android:layout_weight="1" android:gravity="center" android:textSize="20sp" android:hint="姓名" />
                <EditText android:id="@+id/edit_tel" android:layout_width="wrap_content" android:layout_height="wrap_content"
                    android:layout_weight="1" android:gravity="center" android:textSize="20sp" android:hint="電話" />
                <EditText android:id="@+id/edit_height" android:layout_width="wrap_content" android:layout_height="wrap_content"
                    android:layout_weight="1" android:gravity="center" android:textSize="20sp" android:hint="身高" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >
                <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="創表" />
                <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="插入" />
                <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="刪除" />
                <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="更新" />
                <Button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="查詢" />
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>

    <!-- 顯示列表 -->
    <RelativeLayout
        android:id="@+id/Content_Layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/MyLayout_bottom"
        android:layout_below="@id/MyLayout_top"
        android:background="#EFDFDF" >
        <ListView
            android:id="@+id/listview1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center" >
        </ListView>
    </RelativeLayout>
</RelativeLayout>

接著在 res/layout 中新增 ListView 使用的 stu_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView android:id="@+id/stu_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" />
    <TextView android:id="@+id/stu_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" />
    <TextView android:id="@+id/stu_tel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" />
    <TextView android:id="@+id/stu_height" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" />
</LinearLayout>

然後定義自訂的 MySQLiteOpenHelper,負責建表與版本升級:

// 添加自定義類 繼承 SQLiteOpenHelper
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    public Context mContext;
    // 創建學生表(學號,姓名,電話,身高) 主鍵學號
    public static final String createTableStu = "create table Student (" +
            "id integer primary key, " +
            "name text, " +
            "tel text, " +
            "height real)";
    // 抽象類 必須定義顯示的構造函數 重寫方法
    public MySQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }
    @Override
    public void onCreate(SQLiteDatabase arg0) {
        arg0.execSQL(createTableStu);
        Toast.makeText(mContext, "Created", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        arg0.execSQL("drop table if exists Student");
        onCreate(arg0);
        Toast.makeText(mContext, "Upgraged", Toast.LENGTH_SHORT).show();
    }
}

最後是 MainActivity.java,把五顆按鈕各自綁上對應操作:

public class MainActivity extends Activity {
    // 繼承 SQLiteOpenHelper 類
    private MySQLiteOpenHelper sqlHelper;
    private ListView listview;
    private EditText edit1;
    private EditText edit2;
    private EditText edit3;
    private EditText edit4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sqlHelper = new MySQLiteOpenHelper(this, "StuDatabase.db", null, 2);

        // 建立新表
        Button createBn = (Button) findViewById(R.id.button1);
        createBn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sqlHelper.getWritableDatabase();
            }
        });

        // 插入數據
        Button insertBn = (Button) findViewById(R.id.button2);
        edit1 = (EditText) findViewById(R.id.edit_id);
        edit2 = (EditText) findViewById(R.id.edit_name);
        edit3 = (EditText) findViewById(R.id.edit_tel);
        edit4 = (EditText) findViewById(R.id.edit_height);
        insertBn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = sqlHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("id", edit1.getText().toString());
                values.put("name", edit2.getText().toString());
                values.put("tel", edit3.getText().toString());
                values.put("height", edit4.getText().toString());
                db.insert("Student", null, values);
                Toast.makeText(MainActivity.this, "數據插入成功", Toast.LENGTH_SHORT).show();
                edit1.setText("");
                edit2.setText("");
                edit3.setText("");
                edit4.setText("");
            }
        });

        // 刪除數據
        Button deleteBn = (Button) findViewById(R.id.button3);
        deleteBn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = sqlHelper.getWritableDatabase();
                db.delete("Student", "height > ?", new String[] {"180"});
                Toast.makeText(MainActivity.this, "刪除數據", Toast.LENGTH_SHORT).show();
            }
        });

        // 更新數據
        Button updateBn = (Button) findViewById(R.id.button4);
        updateBn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = sqlHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("height", "180");
                db.update("Student", values, "name = ?", new String[] {"XiaoMing"});
                Toast.makeText(MainActivity.this, "更新數據", Toast.LENGTH_SHORT).show();
            }
        });

        // 查詢數據
        listview = (ListView) findViewById(R.id.listview1);
        Button selectBn = (Button) findViewById(R.id.button5);
        selectBn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    SQLiteDatabase db = sqlHelper.getWritableDatabase();
                    // 游標查詢每條數據
                    Cursor cursor = db.query("Student", null, null, null, null, null, null);
                    // 定義 list 存儲數據
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    // 適配器 SimpleAdapter 數據綁定
                    // 注意:構造函數 SimpleAdapter 未定義,需把 this 修改為 MainActivity.this
                    SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list, R.layout.stu_item,
                            new String[]{"id", "name", "tel", "height"},
                            new int[]{R.id.stu_id, R.id.stu_name, R.id.stu_tel, R.id.stu_height});
                    // 讀取數據 游標移動到下一行
                    while (cursor.moveToNext()) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", cursor.getString(cursor.getColumnIndex("id")));
                        map.put("name", cursor.getString(cursor.getColumnIndex("name")));
                        map.put("tel", cursor.getString(cursor.getColumnIndex("tel")));
                        map.put("height", cursor.getString(cursor.getColumnIndex("height")));
                        list.add(map);
                    }
                    listview.setAdapter(adapter);
                } catch (Exception e) {
                    Log.i("exception", e.toString());
                }
            }
        });
    }
}

幾個實作時容易踩到的重點:

・SimpleAdapter 的第一個參數在匿名內部類別中不能直接寫 this,必須改成 MainActivity.this,否則會出現「構造函數未定義」的編譯錯誤。
・whereClause 使用佔位符(例如 "height > ?")時,後面必須搭配 whereArgs 陣列,寫法比字串拼接安全,也能避免 SQL 注入。
・版本升級:只要改了 MySQLiteOpenHelper 建構子中的 version 數字,就會觸發 onUpgrade(),實務上要視需求決定是重建資料表還是做資料遷移。
・記得關閉 Cursor:查詢完畢後呼叫 cursor.close(),避免游標洩漏。

本文涵蓋的是 SQLite 的基礎操作,尚未觸及觸發器、預存程序、交易、索引等進階主題。搭配郭霖《第一行代碼 Android》等書籍一起閱讀,效果會更好。

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