數(shù)據(jù)持久化-數(shù)據(jù)庫(kù)基礎(chǔ)SQLiteOpenHelper

Android基礎(chǔ)的SQLite使用

1. SQLiteOpenHelper

  1. 借助該類實(shí)現(xiàn)數(shù)據(jù)庫(kù)創(chuàng)建與升級(jí)
  2. 通過繼承實(shí)現(xiàn)該類獲取數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)操作
方法 描述 備注
SQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable CursorFactory factory, int version) 構(gòu)造方法 上下文、數(shù)據(jù)庫(kù)名、游標(biāo)工廠類(默認(rèn)null)、數(shù)據(jù)庫(kù)版本號(hào)
onCreate(SQLiteDatabase db) 創(chuàng)建數(shù)據(jù)庫(kù) 使用db執(zhí)行設(shè)計(jì)配置好的數(shù)據(jù)庫(kù)建表語句進(jìn)行建表
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 升級(jí)數(shù)據(jù)庫(kù) 根據(jù)版本號(hào)不同進(jìn)行升級(jí),發(fā)生在App低版本升級(jí)數(shù)據(jù)庫(kù)結(jié)構(gòu)有改變的情況下

2. 使用 CRUD Create Retrieve Update Delete

1.getWritableDatabase()與getReadableDatabase()

創(chuàng)建或打開一個(gè)現(xiàn)有的數(shù)據(jù)庫(kù)(如果已存在直接打開,否則創(chuàng)建一個(gè)),并返回一個(gè)可對(duì)數(shù)據(jù)庫(kù)進(jìn)行讀寫操作的對(duì)象;當(dāng)數(shù)據(jù)庫(kù)不可寫入時(shí)(磁盤空間已滿),getWritableDatabase()會(huì)出現(xiàn)異常,getReadableDatabase()返回的對(duì)象將已只讀的方式打開

2.long insert(String table, String nullColumnHack, ContentValues values)

插入表名,自動(dòng)賦值null(用于未指定添加數(shù)據(jù)的情況下給可空列自動(dòng)賦值),數(shù)據(jù)集合

ContentValues contentValues = new ContentValues(); 
contentValues.put("name","日常消費(fèi)");
contentValues.put("details","飲食#水果#衣物"); 
DBUtils.insert(DBTables.TABLE_ACCOUNT_SORT,null, contentValues);

3.int delete(String table, String whereClause, String[] whereArgs)

表名,條件,條件字符串組

DBUtils.delete(DBTables.TABLE_ACCOUNT_SORT,"name = ?",new String[]{"日常消費(fèi)"});

4.int update(String table, ContentValues values, String whereClause, String[] whereArgs)

表名,更新的值集合,條件,條件字符串組

ContentValues contentValues = new ContentValues();
contentValues.put("details","飲食#水果#衣物#交通"); 
DBUtils.update(DBTables.TABLE_ACCOUNT_SORT, contentValues, "name = ?", new String[]{"日常消費(fèi)"});

5.Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)

查詢表名,指定的列名(不指定默認(rèn)查詢所有列,約束條件(約束查詢某一行或某幾行的數(shù)據(jù),默認(rèn)查詢所有行),條件字符串集,指定分組的列(用于獲取分組匯總),分組匯總的進(jìn)一步篩選,查詢結(jié)果指定排序

   Cursor cursor = DBUtils.query(DBTables.TABLE_ACCOUNT_SORT, null, null, null, null, null, null);
       if (cursor.moveToFirst()) {
           do {
               String name = cursor.getString(cursor.getColumnIndex("name"));
               String details = cursor.getString(cursor.getColumnIndex("details"));
               Log.e(TAG, "name: " + name);
               Log.e(TAG, "details: " + details);
           }while (cursor.moveToNext());
           cursor.close();
       }

3. 封裝

  1. DBHelper

    public class DBHelper extends SQLiteOpenHelper {
        public DBHelper(Context context) {
            super(context, DBTables.DB_NAME, null, DBTables.DB_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DBTables.ACCOUNT_SQL);
            db.execSQL(DBTables.ACCOUNT_SORT_SQL);
            db.execSQL(DBTables.ACCOUNT_DETAIL_SQL);
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        }
    }
    
  2. DBTables

    public interface DBTables {
        String DB_NAME = "db.sqlite";
        int DB_VERSION = 1;
        String TABLE_ACCOUNT = "account";
        String ACCOUNT_SQL = "create table "+TABLE_ACCOUNT+"(" +
                "id integer primary key autoincrement," +
                "date varchar(20)," +
                "sort varchar(10)," +
                "detail varchar(10)," +
                "sum varchar(10)," +
                "source varchar(10)," +
                "income integer," +
                "type varchar(10)," +
                "reason varchar(10)," +
                "remark varchar(60)" +
                ")";
        String TABLE_ACCOUNT_SORT = "sort";
        String ACCOUNT_SORT_SQL = "create table "+TABLE_ACCOUNT_SORT+"(" +
                "name varchar(10) primary key," +
                "details varchar(100)" +
                ")";
        String TABLE_ACCOUNT_DETAIL = "detail";
        String ACCOUNT_DETAIL_SQL = "create table "+TABLE_ACCOUNT_DETAIL+"(" +
                "name varchar(10) primary key," +
                "budget varchar(100)" +
                ")";
    }
    
  3. DBUtils

    /**
     * Created by SJ on 2019/1/22.
     * 使用時(shí)需要在Application中初始化
     * 查詢操作時(shí) 需要及時(shí)關(guān)閉游標(biāo)與數(shù)據(jù)庫(kù)
     */
    public class DBUtils {
        private static DBHelper dbHelper;
        public static void init(Context context) {
            if (dbHelper == null) {
                dbHelper = new DBHelper(context);
            }
        }
        private static SQLiteDatabase getReadableDatabase() {
            if (dbHelper != null) {
                return dbHelper.getReadableDatabase();
            }else {
                throw new SQLException("DBUtils未初始化!");
            }
        }
    
        /**
         * 執(zhí)行增刪改SQL語句
         * @param sql
         */
        public static void execSQL(String sql) {
            SQLiteDatabase db = getReadableDatabase();
            db.execSQL(sql);
            db.close();
        }
    
        /**
         * 執(zhí)行增刪改SQL語句
         * @param sql 帶占位符的語句
         * @param bindArgs  實(shí)際value
         */
        public static void execSQL(String sql, Object[] bindArgs) {
            SQLiteDatabase db = getReadableDatabase();
            db.execSQL(sql, bindArgs);
            db.close();
        }
        /**
         * @param table 表名
         * @param nullColumnHack 指定為null的列
         * @param values 添加的值集合
         */
        public static void insert(String table, String nullColumnHack, ContentValues values) {
            SQLiteDatabase db = getReadableDatabase();
            db.insert(table,nullColumnHack,values);
            db.close();
        }
    
        /**
         * 刪除
         * @param table 表名
         * @param whereClause 刪除條件
         * @param whereArgs 條件對(duì)應(yīng)值
         */
        public static void delete(String table, String whereClause, String[] whereArgs) {
            SQLiteDatabase db = getReadableDatabase();
            db.delete(table,whereClause,whereArgs);
            db.close();
        }
    
        /**
         * 修改
         * @param table 表名
         * @param values 需要修改的值
         * @param whereClause 條件
         * @param whereArgs 條件對(duì)應(yīng)值
         */
        public static void update(String table, ContentValues values, String whereClause, String[] whereArgs) {
            SQLiteDatabase db = getReadableDatabase();
            db.update(table, values, whereClause, whereArgs);
            db.close();
        }
    
        /**
         *
         * @param table         String:表名
         * @param columns       String[]:要查詢的列名
         * @param selection     String:查詢條件
         * @param selectionArgs String[]:查詢條件的參數(shù)
         * @param groupBy       String:對(duì)查詢的結(jié)果進(jìn)行分組
         * @param having        String:對(duì)分組的結(jié)果進(jìn)行限制
         * @param orderBy       String:對(duì)查詢的結(jié)果進(jìn)行排序
         * @return 返回游標(biāo),使用后需要及時(shí)關(guān)閉游標(biāo)
         */
        public static Cursor query(String table, String[] columns, String selection,
                                   String[] selectionArgs, String groupBy, String having,
                                   String orderBy){
            SQLiteDatabase db = getReadableDatabase();
            return db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
        }
    
        /**
         * @param sql 帶占位符的查詢語句
         * @param selectionArgs 查詢條件實(shí)際值
         * @return 返回游標(biāo),使用后需要及時(shí)關(guān)閉游標(biāo)
         */
        public static Cursor rawQuery(String sql, String[] selectionArgs){
            SQLiteDatabase db = getReadableDatabase();
            return db.rawQuery(sql,selectionArgs);
        }
    
        public static void colseDB(){
            dbHelper.close();
        }
    }
    
  4. 使用代碼及結(jié)果

            ContentValues contentValues = new ContentValues();
            contentValues.put("name", "日常消費(fèi)");
            contentValues.put("details", "飲食#水果#衣物");
            DBUtils.insert(DBTables.TABLE_ACCOUNT_SORT, null, contentValues);
            contentValues.clear();
            contentValues.put("details", "飲食#水果#衣物#交通");
            DBUtils.update(DBTables.TABLE_ACCOUNT_SORT, contentValues, "name = ?", new String[]{"日常消費(fèi)"});
            Cursor cursor = DBUtils.query(DBTables.TABLE_ACCOUNT_SORT, null, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    String details = cursor.getString(cursor.getColumnIndex("details"));
                    Log.e(TAG, "name: " + name);
                    Log.e(TAG, "details: " + details);
                } while (cursor.moveToNext());
                cursor.close();
            }
            DBUtils.delete(DBTables.TABLE_ACCOUNT_SORT, "name = ?", new String[]{"日常消費(fèi)"});
    
    image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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