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

在 Android 中使用 SQLite:從建表到增刪改查的完整示範

編輯:關於 Android 開發

SQLite 輕量、體積小,幾乎成了行動端的預設選擇。Android 系統本身就內建了 SQLite,不像在 Cocos2d-x 中還得自己塞外部庫,用起來相當省事。本文用一個小 demo 把建庫、建表、插入、刪除、更新、查詢六件事走一遍。

成品長這樣

啟動 App 後是一個垂直排列的按鈕列表,每個按鈕對應一個資料庫操作:

點擊 createDatabase 後,logcat 會印出「數據庫創建成功」。再點一次則不會重複印,因為 SQLiteOpenHelper 只在首次建立時呼叫 onCreate。

資料庫檔會出現在應用包的 databases 目錄下:

把 people.db 拉出來,用 SQLite Expert 之類的工具打開,就能看到內容。按 Insert 後可見十筆學生資料:

按 Delete 會刪除「劉得意」這筆紀錄:

按 Update 會把所有學生的學號各減一:

按 Select 則查詢所有學生姓名與對應的 C++ 成績,印在 logcat 中:

一、佈局檔

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.fyt.databasedemo.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="createDatabase"
        android:text="createDatabase"
        android:textSize="30dp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Insert"
        android:text="Insert"
        android:textSize="30dp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Delete"
        android:text="Delete"
        android:textSize="30dp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Update"
        android:text="Update"
        android:textSize="30dp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Select"
        android:text="Select"
        android:textSize="30dp" />
</LinearLayout>

二、MyOpenHelper:繼承 SQLiteOpenHelper

建表邏輯寫在 onCreate 中,升級邏輯寫在 onUpgrade 中,兩者都由框架代為呼叫。

package com.fyt.databasedemo;

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

public class MyOpenHelper extends SQLiteOpenHelper {

    /**
     * @param context 上下文
     * @param name    資料庫檔名
     * @param factory 游標工廠(結果集)
     * @param version 資料庫版本號,用於升級判斷
     */
    public MyOpenHelper(Context context, String name,
                        SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    // 建立資料庫時呼叫
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("MainActivity", "數據庫創建成功");
        db.execSQL("create table student(_id integer primary key autoincrement, "
                + "name char(10), age integer, no integer, "
                + "cpp float, math float, english float)");
    }

    // 資料庫升級時呼叫
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("MainActivity", "數據庫升級成功");
    }
}

三、MainActivity:六個操作

package com.fyt.databasedemo;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

    private MyOpenHelper oh;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 建立(或開啟)資料庫
    public void createDatabase(View view) {
        oh = new MyOpenHelper(this, "people.db", null, 1);
        db = oh.getWritableDatabase();
    }

    // 新增資料:使用佔位符參數,避免 SQL 注入與拼字錯誤
    public void Insert(View view) {
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"劉得意", 19, 1001, 60, 98, 75});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"王銳", 20, 1002, 63, 90, 96});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"何煜中", 19, 1003, 90, 73, 82});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"王磊", 21, 1004, 87, 86, 92});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"馮松", 19, 1005, 89, 98, 83});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"裴培", 20, 1006, 75, 82, 91});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"馬驍", 19, 1007, 62, 67, 90});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"馬婧", 20, 1008, 98, 84, 87});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"周俊升", 19, 1009, 57, 68, 96});
        db.execSQL("insert into student(name, age, no, cpp, math, english) "
                        + "values(?, ?, ?, ?, ?, ?)",
                new Object[]{"賀祺", 21, 1010, 61, 96, 72});
    }

    // 刪除指定條件的資料
    public void Delete(View view) {
        db.execSQL("delete from student where name = ?",
                new Object[]{"劉得意"});
    }

    // 更新資料
    public void Update(View view) {
        db.execSQL("update student set no = no - 1");
    }

    // 查詢資料
    public void Select(View view) {
        Cursor cursor = db.rawQuery("select name, cpp from student", null);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            float cpp = cursor.getFloat(cursor.getColumnIndex("cpp"));
            Log.d("MainActivity", "[" + name + ", " + cpp + "]");
        }
        cursor.close(); // 別忘了關閉游標,否則會洩漏
    }
}

幾個實務提醒

示範中每個操作都用 execSQL 帶佔位符參數,這是好習慣,比字串拼接安全得多。大量寫入時建議包在 beginTransaction() / setTransactionSuccessful() / endTransaction() 之間,效能差距會很明顯。查詢用的 Cursor 用完要關,Activity 銷毀時也記得呼叫 db.close()。若想省事,也可以改用 insert()、delete()、update()、query() 這組高階 API,不必自己寫 SQL 字串。

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