SQLit數(shù)據(jù)庫(kù) 增 刪 改 查

SQLite數(shù)據(jù)庫(kù)

  • Sqlite簡(jiǎn)介
    Sqlite是一款輕型的數(shù)據(jù)庫(kù),它包含在一個(gè)相對(duì)小的C庫(kù)中,它的設(shè)計(jì)目標(biāo)是嵌入式的,由于它占用資源非常少,可能只需要幾百K的內(nèi)存就可以了,并且支持Windows/Linux/Unix等等主流的操作系統(tǒng),同時(shí)可以和很多種程序語(yǔ)言相結(jié)合,比如:C#/Java/php等,所以在嵌入式設(shè)備中特別受歡迎,這一點(diǎn)也正好符合android的開發(fā)要求,所以在Android開發(fā)中經(jīng)常要用到該數(shù)據(jù)庫(kù)。

  • SQlite內(nèi)部結(jié)構(gòu)
    在內(nèi)部,Sqlite有以下幾個(gè)組件組成:SQL編譯器、內(nèi)核、后端以及附件。Sqlite通過(guò)利用虛擬機(jī)和虛擬數(shù)據(jù)庫(kù)引擎,是調(diào)試、修改和擴(kuò)展Sqlite的內(nèi)核變得更加方便,所有SQL語(yǔ)句被編譯成易讀的、可以在Sqlite虛擬機(jī)中執(zhí)行的程序集。

  • android中Sqlite的使用方法
    在Android中要想使用Sqlite數(shù)據(jù)庫(kù),首先應(yīng)該創(chuàng)建一個(gè)類繼承SQLiteOpenHelper類,我們把這個(gè)類命名為DatabaseHelper,它作為一個(gè)訪問(wèn)Sqlite的助手類,提供了兩方面的功能:

    • getReadableDatabase()/getWritableDatabase()可以獲得SQLiteDatabase對(duì)象,通過(guò)該對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作;
    • 提供OnCreate()和onUpgrade()兩個(gè)回調(diào)函數(shù),允許我們?cè)趧?chuàng)建和升級(jí)數(shù)據(jù)庫(kù)時(shí),進(jìn)行自己的操作;
范例:
  • 數(shù)據(jù)庫(kù)助手類
  • 自定義MySQLiteOpenHelper類 繼承SQLiteOpenHelper
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    // 數(shù)據(jù)庫(kù)文件名
    private final static String DB_NAME = "my_database.db";
    // 數(shù)據(jù)庫(kù)版本號(hào)
    private final static int DB_VERSION = 1;
    // 數(shù)據(jù)庫(kù)表名
    public final static String TABLE_NAME = "table_person";

    /**
     * 創(chuàng)建數(shù)據(jù)庫(kù)文件
     *
     * @param context 上下文
     * @param name    數(shù)據(jù)庫(kù)文件名
     * @param factory 游標(biāo)工廠, 如果為null,Android系統(tǒng)提供默認(rèn)的游標(biāo)
     * @param version 數(shù)據(jù)庫(kù)版本號(hào)
     */
    public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    //創(chuàng)建數(shù)據(jù)庫(kù)文件:
    public MySQLiteOpenHelper(Context context) {
        //創(chuàng)建了名為"my_database.db"數(shù)據(jù)庫(kù),版本號(hào) 1  數(shù)據(jù)庫(kù)地址: data/data/com.w.Demo/databases/my_database.db
        super(context, DB_NAME, null, DB_VERSION);
    }

    /**
     * 創(chuàng)建了數(shù)據(jù)庫(kù)
     * @param db 系統(tǒng)返回的數(shù)據(jù)庫(kù)對(duì)象
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // 創(chuàng)建表語(yǔ)句,語(yǔ)義:如果不存在則創(chuàng)建表,字段包括:主鍵_id,name,age
        /*注意: SQ語(yǔ)句: exists后面空格,()不要忘記*/
        String sql = "create table if not exists " + TABLE_NAME + "(_id integer primary key autoincrement, name varchar, age integer)";
        // 執(zhí)行創(chuàng)建表的數(shù)據(jù)庫(kù)語(yǔ)句
        db.execSQL(sql);
    }

    /**
     * @param db  系統(tǒng)返回的數(shù)據(jù)庫(kù)對(duì)象
     * @param oldVersion 舊版本
     * @param newVersion 新版本
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion != newVersion) {
            Log.d("TAG", "onUpgrade: onUpgrade");
        }
    }
}
  • 使用數(shù)據(jù)助手類創(chuàng)建數(shù)據(jù)庫(kù)
MySQLiteOpenHelper mHelper =  new MySQLiteOpenHelper(this);
SQLiteDatabase dbSelect = mHelper.getReadableDatabase();
  • 具體增刪改查見(jiàn)下:

  • 創(chuàng)建或打開數(shù)據(jù)庫(kù)的方法

public SQLiteDatabase getDb() {
 //創(chuàng)建數(shù)據(jù)庫(kù) my_database.db
        String filePath = Environment.getExternalStorageDirectory() + "/my_database.db";
        SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(filePath, null);
 //在數(shù)據(jù)庫(kù)中創(chuàng)建一張表 table_person
        String sql = "create table if not exists table_person(_id integer primary key autoincrement, name varchar, age integer)";
 // 執(zhí)行創(chuàng)建表的數(shù)據(jù)庫(kù)語(yǔ)句
        database.execSQL(sql);
        return database;
}
  • 插入數(shù)據(jù)
    • 插入單條數(shù)據(jù)
SQLiteDatabase dbAdd = getDb();
ContentValues values = new ContentValues();
                values.put("name", "林志玲");
                values.put("age", 18);
                // table:要插入數(shù)據(jù)的表名
                //nullColumnHack:當(dāng)插入數(shù)據(jù)為null時(shí),nullColumnHack不允許為空,通過(guò)系統(tǒng)的處理保證了程序的穩(wěn)定性;當(dāng)插入數(shù)據(jù)不為null時(shí),nullColumnHack排不上用場(chǎng),為null
                // values:插入的數(shù)據(jù)
                dbAdd.insert("table_person", null, values);
  • 使用SQ語(yǔ)句插入多條數(shù)據(jù)
//得到數(shù)據(jù)庫(kù)
  SQLiteDatabase dbAdd = getDb();
                // 開始事務(wù)
                dbAdd.beginTransaction();
                try {
                    for (int i = 0; i < 10; i++) {
                        // 插入數(shù)據(jù)
                        String sql = "insert into table_person(name, age) values('林志玲', " + i + ")";
                        dbAdd.execSQL(sql);
                    }
                   //事務(wù)成功
                    dbAdd.setTransactionSuccessful();
                } catch (Exception e) {

                } finally {
                    //結(jié)束事務(wù)
                    dbAdd.endTransaction();
                }
                //關(guān)閉數(shù)據(jù)庫(kù),節(jié)約內(nèi)存資源
                dbAdd.close();
  • Transaction事務(wù): 事務(wù)開始和結(jié)束之間的代碼要嗎全部執(zhí)行要么不執(zhí)行

  • 刪除數(shù)據(jù)

 SQLiteDatabase dbDelete = getDb();
                // 刪除數(shù)據(jù)庫(kù)指定表中的數(shù)據(jù)
                // table:表名
                // whereClause:刪除條件,格式“name = ?”
                // whereArgs:滿足刪除的條件,即刪除的數(shù)據(jù),格式“"張三"”
                dbDelete.delete("table_person", "name = ?", new String[]{"林志玲"});
                dbDelete.close();
  • 修改數(shù)據(jù)
ContentValues contentValues = new ContentValues();
                contentValues.put("name", "張三");
                contentValues.put("age", 25);
                SQLiteDatabase dbModify = getDb();
                // table:表名
                // values:更新的數(shù)據(jù)
                // whereClause:更新條件
                // whereArgs:滿足更新的條件
                dbModify.update("table_person", contentValues, "name = ?", new String[]{"林志玲"});
                dbModify.close();
  • 查詢數(shù)據(jù)
               //得到數(shù)據(jù)庫(kù);
                SQLiteDatabase dbSelect = getDb();
              // 查詢數(shù)據(jù)庫(kù)
                // table:表名
                // columns:被查詢的列(字段),可以有很多個(gè)
                // selection:查詢條件
                // selectionArgs:滿足查詢的條件
                // groupBy:指定分組(多數(shù)情況不使用)
                // having:分組篩選數(shù)據(jù)關(guān)鍵字(多數(shù)情況不使用)
                // orderBy:排序
                Cursor cursor = dbSelect.query("table_person", new String[]{"name", "age"}, null, null, null, null, null);
                int nameIndex = cursor.getColumnIndex("name");
                int ageIndex = cursor.getColumnIndex("age");
                //遍歷數(shù)據(jù)庫(kù)查詢數(shù)據(jù)  
                while (cursor.moveToNext()) {
                    String name = cursor.getString(nameIndex);
                    int age = cursor.getInt(ageIndex);
                   showText = showText + "姓名: " + name + "\t年齡: " + age + "\n";
                }
                 Log.d("TAG", "數(shù)據(jù): " + showText );
                dbSelect.close();
                cursor.close();

-注意事項(xiàng):

  • 若使用自定義的數(shù)據(jù)庫(kù)助手類創(chuàng)建了數(shù)據(jù)庫(kù),數(shù)據(jù)庫(kù)存儲(chǔ)的位置為** data/data/com.w.Demo/databases/my_database.db**
  • 若使用創(chuàng)建或打開數(shù)據(jù)庫(kù)的方法,數(shù)據(jù)庫(kù)的位置為:/storage/emulated/0/my_database.db
最后編輯于
?著作權(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)容