數(shù)據(jù)存儲學(xué)習(xí)筆記

Sqlite

使用
  1. 創(chuàng)建數(shù)據(jù)庫
  2. 創(chuàng)建表

Android為了讓我們能方便的管理數(shù)據(jù)庫,提供了一個SQLiteOpenHelper幫助類,借助這個類就可以非常簡單地對數(shù)據(jù)庫進(jìn)行創(chuàng)建和升級,所以我們需要先繼承 SQLiteOpenHelper 寫一個 DatabaseHelper,代碼如下:

public class DatabaseHelper extends SQLiteOpenHelper{


    /**
     * 先把建表語句用字符串變量存起(也可以不存,直接在函數(shù)里寫,但這樣規(guī)范些)
     */
    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 DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.mContext = context;
        Log.d(LogUtil.TAG,"DatabaseHelper");
    }

    /**
     * 第一次創(chuàng)建數(shù)據(jù)庫時執(zhí)行,如果數(shù)據(jù)庫已經(jīng)存在,則不在執(zhí)行
     * @param sqLiteDatabase
     */
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        sqLiteDatabase.execSQL(CREATE_BOOK);
        sqLiteDatabase.execSQL(CREATE_CATEGORY);

        Log.d(LogUtil.TAG,"onCreate");
        Toast.makeText(mContext,"Created succeded",Toast.LENGTH_SHORT).show();
    }

    /**
     * 此方法升級數(shù)據(jù)庫時會被回調(diào)
     * @param sqLiteDatabase
     * @param i
     * @param i1
     */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        Log.d(LogUtil.TAG,"onUpgrade");

        sqLiteDatabase.execSQL("drop table if exists Book");
        sqLiteDatabase.execSQL("drop table if exists Category");
        onCreate(sqLiteDatabase);
    }

    /**
     * 每次打開數(shù)據(jù)庫時都會執(zhí)行,也就是
     * DbHelper.getWritableDatabase() 或 mDbHelper.getReadableDatabase()
     * @param db
     */
    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        Log.d(LogUtil.TAG,"onOpen");
    }
}

上面的注釋寫的比較詳細(xì),把每個方法都寫到了,相信應(yīng)該能看懂。

然后需要調(diào)用創(chuàng)建DatabaseHelper的實(shí)例,然后通過DatabaseHelper來獲得SQLiteDatabase實(shí)例,我們就可以使用返回的SQLiteDatabase實(shí)例來操作數(shù)據(jù)庫了

//參數(shù)一:Context
//參數(shù)二:數(shù)據(jù)庫名稱
//參數(shù)三:允許我們在查詢數(shù)據(jù)時返回一個自定義的Cursor,一般用不到,傳入null
//參數(shù)四:版本號
DatabaseHelper mDbHelper = new DatabaseHelper(this,"BookStore.db",null,2);

//一般是getWritableDatabase()
mDb = mDbHelper.getWritableDatabase()   或  mDbHelper.getReadableDatabase()
  1. 升級數(shù)據(jù)庫
//修改版本號就行
DatabaseHelper mDbHelper = new DatabaseHelper(this,"BookStore.db",null,3);  // 下次升級就把 3 改成更大的
  1. 增加數(shù)據(jù)(insert)
//用contentValues來保存你需要存儲的數(shù)據(jù)
ContentValues contentValues = new ContentValues();
contentValues.put("pages",pages);
contentValues.put("price",price);

//參數(shù)一:表名
//參數(shù)二:用于在未指定添加數(shù)據(jù)的情況下給某些可為空的列自動賦值null,一般用不到,設(shè)為null
//參數(shù)三:ContentValues對象

mDb.insert("Book",null,contentValues);

//清空contentValues
contentValues.clear();
  • 查詢數(shù)據(jù)(select)

SQLiteDatabase中提供了一個query()方法用于對數(shù)據(jù)進(jìn)行查詢,這個方法參數(shù)比較復(fù)雜,最短的一個也需要傳7個參數(shù),界面來介紹一個7個參數(shù)的含義:

  1. table :指定查詢的表名
  2. columns :指定查詢的列名
  3. selection :指定where的約束條件
  4. selectionArgs :為where重的占位符提供具體的值
  5. groupBy :指定需要group by的列
  6. having :對group by后的結(jié)果進(jìn)一步約束
  7. orderBy :指定查詢結(jié)果的排列方式

以下是查詢數(shù)據(jù)的代碼片段:

mSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mDb == null){
                    mDb = mDbHelper.getWritableDatabase();  //創(chuàng)建或打開數(shù)據(jù)庫
                }

                name = mEdit_Name.getText().toString();

                Cursor cursor = mDb.query("Book",null,"name = ?",new String[]{name},null,null,null);
                if (cursor.moveToFirst()){
                    do {
                        name = cursor.getString(cursor.getColumnIndex("name"));
                        author = cursor.getString(cursor.getColumnIndex("author"));
                        pages = cursor.getString(cursor.getColumnIndex("pages"));
                        price = cursor.getString(cursor.getColumnIndex("price"));

                        mTv_Name.setText(name);
                        mTv_Author.setText(author);
                        mTv_Pages.setText(pages);
                        mTv_Price.setText(price);

                    }while (cursor.moveToNext());
                }
            }
        });
  • 更新數(shù)據(jù)(update)

update()函數(shù)有4個參數(shù),和query()的大部分相同

  1. table:指定查詢的表名
  2. values:刷新的值
  3. whereClause:指定where的約束條件
  4. whereArgs:為where重的占位符提供具體的值

以下是更新數(shù)據(jù)的代碼片段:

mUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mDb == null){
                    mDb = mDbHelper.getWritableDatabase();  //創(chuàng)建或打開數(shù)據(jù)庫
                }

                name = mEdit_Name.getText().toString();
                author = mEdit_Author.getText().toString();
                pages = mEdit_Pages.getText().toString();
                price = mEdit_Price.getText().toString();

                if (!"".equals(author))contentValues.put("author",author);
                if (!"".equals(pages))contentValues.put("pages",pages);
                if (!"".equals(price))contentValues.put("price",price);

                mDb.update("Book",contentValues,"name = ?",new String[]{name});

                contentValues.clear();
            }
        });
  • 刪除數(shù)據(jù)(delete)

delete()方法有3個參數(shù),和上面的一樣,就不細(xì)說了,代碼如下:

mDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mDb == null){
                    mDb = mDbHelper.getWritableDatabase();  //創(chuàng)建或打開數(shù)據(jù)庫
                }

                name = mEdit_Name.getText().toString();

                mDb.delete("Book","name = ?",new String[]{name});
            }
        });
問題:
  • getReadableDatabase() 和 getWritableDatabase() 的區(qū)別?
  1. 兩個方法都可以創(chuàng)建或打開一個現(xiàn)有的數(shù)據(jù)庫(如果數(shù)據(jù)庫已存在則直接打開,否則創(chuàng)建一個新的數(shù)據(jù)庫),并返回一個可對數(shù)據(jù)庫進(jìn)行讀寫操作的對象
  2. 當(dāng)數(shù)據(jù)庫不可寫入時(比如磁盤滿了),getReadableDatabase()方法返回的對象將以只讀的方式去打開數(shù)據(jù)庫,而getWritableDatabase()方法則將出現(xiàn)異常。

File

適用場景

文件存儲是Android中最基本的一種數(shù)據(jù)存儲方式,它不對存儲的內(nèi)容進(jìn)行任何的格式化處理,所有的數(shù)據(jù)都是原封不動的保存到文件中,所以它適合存儲一些簡單的文本數(shù)據(jù)或二進(jìn)制數(shù)據(jù)

使用

保存數(shù)據(jù)

openFileOutput()方法可以指定兩種模式:
MODE_PRIVATE:是默認(rèn)的操作模式,表示當(dāng)指定同樣文件名的時候,所寫的內(nèi)容將會覆蓋原文件中的內(nèi)容。
MODE_APPEND:表示如果該文件已存在,就往里面追加內(nèi)容。

private void sava(String inputText){
        FileOutputStream out = null;
        BufferedWriter writer = null;

        try {

            out = openFileOutput("data", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

讀取數(shù)據(jù)

private String load(){
        FileInputStream input = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();

        try {
            input = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(input));
            String line = "";
            while ((line = reader.readLine()) != null){
                content.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return content.toString();
    }

Sharedpreference

不同于文件存儲,Sharedpreference是使用鍵值對的方式來存儲數(shù)據(jù)的,Sharedpreference還支持多種不同的數(shù)據(jù)類型存儲,存的是String取出也是String,存進(jìn)去的是整形,讀取出來也是整形。

使用

獲取Sharedpreference對象

Android中提供了 3 種方法用于得到SharedPreferences對象

  1. Context類 中的 getSharedPreferences()方法
    此方法接收兩個參數(shù):
  • 第一個參數(shù)用于指定Sharedpreference的名稱,如果指定的文件不存在則會創(chuàng)建一個

  • 第二個用于指定操作模式,目前只有
    MODE_PRIVATE 這一模式可選,是默認(rèn)的模式,和直接傳入 0 的效果一樣,表示只有當(dāng)前的應(yīng)用程序才可以對這個Sharedpreference文件進(jìn)行讀寫

  1. Activity類 中的 getPreferences() 方法
    方法1 類似,不過只接收一個操作模式參數(shù),因?yàn)槭褂眠@個方法時會自動將當(dāng)前活動的類名作為 Sharedpreference 的文件名

  2. PreferenceManager 類 中的
    getDefaultSharePreferences() 方法

使用步驟

保存數(shù)據(jù):

(1)、獲取Sharedpreference對象

(2)、調(diào)用Sharedpreference對象的 edit()方法來獲取一個 Sharedpreference.Editor對象。

(3)、向Sharedpreference.Editor對象中添加數(shù)據(jù),比如putBoolean()putString()方法等等

(4)、調(diào)用apply()方法將添加的數(shù)據(jù)提交,從而完成數(shù)據(jù)存儲操作

示例代碼:

SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
                editor.putString("name",mEdit_Name.getText().toString());
                editor.putString("age",mEdit_Age.getText().toString());
                editor.apply();

取出數(shù)據(jù):

(1)、獲取Sharedpreference對象

(2)、調(diào)用Sharedpreference對象的 getString()等方法獲取數(shù)據(jù)

示例代碼:

SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);
                mTv_Name.setText(preferences.getString("name",""));
                mTv_Age.setText(preferences.getString("age",""));
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容