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

Android SQLite 數據庫入門:創建、升級與查看

編輯:關於 Android 程式設計

現在很多應用直接和服務器交互,本地數據庫的存在感似乎降低了。但離線緩存、用戶配置、歷史記錄這些場景仍然離不開 SQLite,作為 Android 開發者還是有必要把它掌握扎實。

一、創建數據庫

Android 提供了 SQLiteOpenHelper 幫助類來簡化數據庫的創建與升級。它是個抽象類——就像只發號施令的領導,自己不幹活,所以必須自定義一個類去繼承它,並實現兩個抽象方法:onCreate() 與 onUpgrade(),分別負責創建與升級。

此外它還提供了兩個重要的實例方法:getReadableDatabase() 與 getWritableDatabase()。兩者都會「打開已有數據庫,不存在則新建」。區別在於:當數據庫不可寫時(例如磁盤已滿),前者以只讀方式打開,後者則會拋出異常。

先看建表語句:

create table Book(
    id integer primary key autoincrement,
    author text,
    price real,
    pages integer,
    name text
)

如果看不太懂,稍微補一下 SQL 基礎即可,並不難。

編寫 MyDatabaseHelper:

package org.lxh.demo;

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

public class MyDatabaseHelper extends SQLiteOpenHelper {

    public static final String CREATE_BOOK = "create table Book("
            + "id integer primary key autoincrement,"
            + "author text, "
            + "price real,"
            + "pages integer,"
            + "name text)";

    private Context mcontext;

    public MyDatabaseHelper(Context context, String name,
                            CursorFactory factory, int version) {
        super(context, name, factory, version);
        mcontext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        Toast.makeText(mcontext, "Create succeeded", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 暫不處理
    }
}

布局裡放一個觸發按鈕:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="創建數據庫" />
</LinearLayout>

MainActivity 中綁定監聽:

package org.lxh.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button create;
    private MyDatabaseHelper myDatabaseHelper;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.main);

        create = (Button) findViewById(R.id.btn);
        myDatabaseHelper = new MyDatabaseHelper(this, "BookStore", null, 1);

        create.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // 調用 getWritableDatabase() 觸發創建
                myDatabaseHelper.getWritableDatabase();
            }
        });
    }
}

點擊按鈕即完成創建。Toast 只會出現一次,因為數據庫也只會被創建一次。

二、更新數據庫

onUpgrade() 就是為了解決「表結構變了」的問題。假設已有 Book 表,現在想再增加一張 Category 表:

package org.lxh.demo;

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

public class MyDatabaseHelper extends SQLiteOpenHelper {

    public static final String CREATE_BOOK = "create table Book("
            + "id integer primary key autoincrement,"
            + "author text, "
            + "price real,"
            + "pages integer,"
            + "name text)";

    public static final String CREATE_CATEGORY = "create table Category ("
            + "id integer primary key autoincrement, "
            + "category_name text, "
            + "category_code integer)";

    private Context mcontext;

    public MyDatabaseHelper(Context context, String name,
                            CursorFactory factory, int version) {
        super(context, name, factory, version);
        mcontext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mcontext, "Create succeeded", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 簡單粗暴的示例做法:先刪後建
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }
}

MainActivity 只需把版本號從 1 改成 2,再次點擊就會觸發 onUpgrade:

myDatabaseHelper = new MyDatabaseHelper(this, "BookStore", null, 2);

三、怎麼確認數據庫真的建好了

用 Android SDK 自帶的 adb 工具即可。先把 platform-tools 目錄加入環境變量:

然後在命令行輸入 adb shell 進入設備控制台:

切換到應用的數據庫目錄:

cd /data/data/org.lxh.demo/databases/

用 sqlite3 打開數據庫文件:

sqlite3 BookStore.db

最後查看所有表:

.table

一點實踐建議

示例中的 onUpgrade 直接 drop 再建,僅適合學習演示——真實項目裡用戶數據不容丟失,正確做法是按 oldVersion 逐級判斷,用 ALTER TABLE 增量遷移。另外,如果數據操作比較頻繁,建議引入 Room 或使用 ContentProvider 對外暴露數據,會比手寫 SQL 更省心。

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