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

Android SQLite 實戰:自訂 DBHelper 封裝增刪查與資料備份

編輯:關於 Android 程式設計

在 Android 應用中,SQLite 是最輕量的本機資料庫方案。本文以一個短信(SMS)管理模組為例,示範如何自訂 DBHelper,把資料庫的開啟、增刪查詢、以及資料備份與還原統一封裝起來。

核心設計思路

整個 DBHelper 對外暴露資料庫操作,內部則透過一個繼承自 SQLiteOpenHelper 的 MyDBHelper 負責建立與升級資料表。資料表名為 sms_content,包含 id、content、chatTime、isComeMsg、type 等欄位。

public class DBHelper {
    public static final String DB_DBNAME = "sms_db";
    public static final String DB_TABLENAME = "sms_content";
    public static final int VERSION = 1;
    public static SQLiteDatabase dbInstance;

    private MyDBHelper myDBHelper;
    private StringBuffer tableCreate;
    private Context context;

    public DBHelper(Context context) {
        this.context = context;
    }

    public void openDatabase() {
        if (dbInstance == null) {
            myDBHelper = new MyDBHelper(context, DB_DBNAME, VERSION);
            dbInstance = myDBHelper.getWritableDatabase();
        }
    }

    // 插入一筆資料
    public long insert(SmSEntity smsEntity) {
        ContentValues values = new ContentValues();
        values.put("content", smsEntity.getContent());
        values.put("chatTime", smsEntity.getChatTime());
        values.put("isComeMsg", smsEntity.getTrueOrfalse());
        values.put("type", smsEntity.getType());
        return dbInstance.insert(DB_TABLENAME, null, values);
    }

    // 查詢全部資料
    public ArrayList<SmSEntity> getAll() {
        ArrayList<SmSEntity> list = new ArrayList();
        String sql = "select * from " + DB_TABLENAME;
        Cursor cursor = dbInstance.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            SmSEntity smSEntity = new SmSEntity();
            smSEntity.setId(cursor.getInt(cursor.getColumnIndex("id")));
            smSEntity.setContent(cursor.getString(cursor.getColumnIndex("content")));
            smSEntity.setChatTime(cursor.getString(cursor.getColumnIndex("chatTime")));
            smSEntity.setTrueOrfalse(cursor.getString(cursor.getColumnIndex("isComeMsg")));
            smSEntity.setType(cursor.getString(cursor.getColumnIndex("type")));
            list.add(smSEntity);
        }
        return list;
    }

    // 刪除單筆
    public void delete(int _id) {
        dbInstance.delete(DB_TABLENAME, "id=?", new String[]{String.valueOf(_id)});
    }

    // 取得總筆數
    public int getTotalCount() {
        Cursor cursor = dbInstance.query(DB_TABLENAME, new String[]{"count(*)"}, null, null, null, null, null);
        cursor.moveToNext();
        return cursor.getInt(0);
    }

    // 內部 SQLiteOpenHelper,負責建表與升級
    class MyDBHelper extends SQLiteOpenHelper {
        public MyDBHelper(Context context, String name, int version) {
            super(context, name, null, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            tableCreate = new StringBuffer();
            tableCreate.append("create table ")
                .append(DB_TABLENAME)
                .append(" (")
                .append("id integer primary key autoincrement,")
                .append("content text,")
                .append("chatTime text,")
                .append("isComeMsg text,")
                .append("type text ")
                .append(")");
            db.execSQL(tableCreate.toString());
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            String sql = "drop table if exists " + DB_TABLENAME;
            db.execSQL(sql);
            onCreate(db);
        }
    }
}

資料備份與還原

除了基本的 CRUD,這個 DBHelper 還支援把資料表內容匯出成一系列 insert 語句並寫入 SD 卡的備份檔;還原時則逐行讀取備份檔並執行 SQL。備份檔依是否為隱私資料分成 priv_data.bk 與 comm_data.bk。

// 備份資料到檔案
public void backupData(boolean privacy) {
    StringBuffer sqlBackup = new StringBuffer();
    // ... 遍歷 Cursor,拼接 insert 語句 ...
    saveDataToFile(sqlBackup.toString(), privacy);
}

private void saveDataToFile(String strData, boolean privacy) {
    String fileName = privacy ? "priv_data.bk" : "comm_data.bk";
    try {
        String SDPATH = Environment.getExternalStorageDirectory() + "/";
        File fileParentPath = new File(SDPATH + "zpContactData/");
        fileParentPath.mkdirs();
        File file = new File(SDPATH + "zpContactData/" + fileName);
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(strData.getBytes());
        fos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 從檔案還原資料
public void restoreData(String fileName) {
    try {
        String SDPATH = Environment.getExternalStorageDirectory() + "/";
        File file = new File(SDPATH + "zpContactData/" + fileName);
        BufferedReader br = new BufferedReader(new FileReader(file));
        String str = "";
        while ((str = br.readLine()) != null) {
            dbInstance.execSQL(str);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

使用方式

在 Activity 中只需建立實例、開啟資料庫,即可呼叫各項操作:

DBHelper dbhelper = new DBHelper(this);
dbhelper.openDatabase();
chatList = dbhelper.getAll();

透過這樣的封裝,資料庫的建表邏輯、CRUD 操作與備份還原都被集中管理,讓上層業務程式碼保持乾淨,也便於日後維護與擴充。

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