Android數據存儲_SQLite數據庫存儲

Android數據存儲的方式有種,主要有三種。分別爲:文件存儲SharedPreference存儲,以及數據庫存儲。

這篇主要講SQLite數據庫存儲。

1.基本描述

        Android自帶了一種輕量級數據庫SQLite。SQLite是一款輕量級的關係型數據庫,他的運算速度非常快,佔用資源很少,通常只需要佔用幾百K的資源就足夠了,因而特別適合在移動設備上使用。SQLite不僅支持標準SQL語法,還遵循了數據庫ACID事務。

        Android爲了讓我們更加方便的使用管理數據庫,專門提供了一個SQLiteOpenHelper幫助類,藉助這個幫助類會非常簡單的對數據庫進行創建和升級。下面我們就通過這幫助類來完成數據庫簡單的使用。

        文件存儲路徑 :data/data/包名/databases/**.db

2.代碼

2.1MyDatabaseHelper

首先我們自己寫一個MyDatabaseHelper繼承SQLiteOpenHelper

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private Context mContext;
    public static final String CREATE_BOOK = "create table Book(" +
            "id integer primary key autoincrement," +
            "auther text," +
            "price real," +
            "pages integer," +
            "name text)";

    public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version, @Nullable DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
        mContext = context;
    }

    public MyDatabaseHelper(@Nullable Context context, @Nullable String name, int version, @NonNull SQLiteDatabase.OpenParams openParams) {
        super(context, name, version, openParams);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        Toast.makeText(mContext, "創建成功", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

       通過代碼可以看出需要重寫onCreate()和onUpgrade()兩個方法。在onCreate()中創建數據庫,在onUpgrade()中升級數據庫。

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

        這個就是創建一個Book表,裏面有幾個字段:id、auther、price、pages、name通過onCreate()中的db.execSQL(CREATE_BOOK);創建表。

2.2創建數據庫和表

1.當首次進入程序沒有創建數據庫和表的時候data/data/包名/沒有數據庫

        我們來創建book表:

myDatabaseHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
create.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        writableDatabase = myDatabaseHelper.getWritableDatabase();
    }
});

同ADM查看:

        確實多了BookStore.db數據庫文件,但是還不能確定有沒有創建book表,我們把他導出到電腦,使用SQLite Expert Professional 3.exe查看。同時還多了一個db-journal是爲了讓數據庫文件能夠支持事務而產生的臨時日誌文件,通常情況下這個文件的大小是0字節。

        可以清晰的看到了BookStore.db數據庫文件裏面有兩個表,一個是android_metadata,這個是數據庫文件都會生成的,另一個Book表就是我們創建的了。

2.3升級數據庫

        眼裏好的同仁已經看到了MyDatabaseHelper中還重寫了onUpgrade()方法。但是沒有用到,這個就是升級表的。因爲當咱們創建好一本表後再次點擊“創建”按鈕的時候確實沒有彈出“創建成功”,通過ADM查看也沒新的數據庫和表生成,這是因爲當沒有這個數據庫的時候會調用onCreate()方法創建,當已經創建了就不能再創建了。

        那麼怎麼才能再次創建呢?這裏只是演示,並不能真正在項目中使用

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private Context mContext;
    public static final String CREATE_BOOK = "create table Book(" +
            "id integer primary key autoincrement," +
            "auther text," +
            "price real," +
            "pages integer," +
            "name text)";

    public static final String CREATE_BOOK1 = "create table Book1(" +
            "id integer primary key autoincrement," +
            "auther text," +
            "price real," +
            "pages integer)";

    public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version, @Nullable DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
        mContext = context;
    }

    public MyDatabaseHelper(@Nullable Context context, @Nullable String name, int version, @NonNull SQLiteDatabase.OpenParams openParams) {
        super(context, name, version, openParams);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_BOOK1);
        Toast.makeText(mContext, "創建成功", 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 Book1");
        onCreate(db);
    }
}

通過onUpgrade先把之前的刪除在重新創建,只是演示因爲刪除數據也沒了。

同時調用的時候將版本號升序。

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

這個時候發現已經多了一張表了Book1.

2.4 插入數據:

add.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", "鋼鐵是怎樣煉成的");
        contentValues.put("pages", 10);
        contentValues.put("price", 9.9);
        contentValues.put("auther", 9.9);
        contentValues.put("auther", "保爾");
        myDatabaseHelper.getWritableDatabase().insert("Book", null, contentValues);
        contentValues.clear();
        contentValues.put("name", "鋼鐵是這樣煉成的");
        contentValues.put("pages", 10);
        contentValues.put("price", 19.9);
        contentValues.put("auther", 9.9);
        contentValues.put("auther", "保爾兒");
        myDatabaseHelper.getWritableDatabase().insert("Book", null, contentValues);
    }
});

2.5 更新數據

updata_data.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("price", 100);
        myDatabaseHelper.getWritableDatabase().update("Book", contentValues, "name = ?", new String[]{"鋼鐵是這樣煉成的"});
    }
});

2.6 刪除數據

del_data.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myDatabaseHelper.getWritableDatabase().delete("Book", "name = ?", new String[]{"鋼鐵是這樣煉成的"});
    }
});

2.7 查詢數據

query_data.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Cursor book = myDatabaseHelper.getWritableDatabase().query("Book", null, null, null, null, null, null);
        if (book.moveToFirst()) {
            do {
                String name = book.getString(book.getColumnIndex("name"));
                int pages = book.getInt(book.getColumnIndex("pages"));
                double price = book.getDouble(book.getColumnIndex("price"));
                String auther = book.getString(book.getColumnIndex("auther"));
                Log.d("TAG", "name:" + name +
                        "pages:" + pages +
                        "price:" + price +
                        "auther:" + auther

                );
            } while (book.moveToNext());
        }

    }
});

SQLiteOpenHelper幫助類雖然已經做的很簡單了,但是用起來還是有些不方便,比如升級數據庫如果用在項目中就需要很複雜的邏輯了,這個時候就會發現一個LitePal一個開源庫了,具體再這裏。

轉發表明出處https://blog.csdn.net/qq_35698774/article/details/106698065

點擊下載源碼

android互助羣:

感謝:郭霖的《第一行代碼 第二版》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章