SQLite及FMDB框架使用簡(jiǎn)介

SQLite作為輕量級(jí)的嵌入式數(shù)據(jù)庫(kù),在移動(dòng)端已經(jīng)普遍使用。其實(shí)數(shù)據(jù)庫(kù)內(nèi)部的樣子,可以把它理解成Excel表格,至于數(shù)據(jù)結(jié)構(gòu)嘛.......囧
數(shù)據(jù)庫(kù)可以分為兩類:
(1)關(guān)系型數(shù)據(jù)庫(kù)
(2)對(duì)象型數(shù)據(jù)庫(kù)
關(guān)系型的是目前使用的主流

其他類型數(shù)據(jù)庫(kù)的介紹:Oracle、MySQL、SQL Server

Navicat
是一款數(shù)據(jù)庫(kù)的管理軟件,支持大部分主流數(shù)據(jù)庫(kù)。

SQLite的語(yǔ)法及基本使用**
在xCode工程中首先要導(dǎo)入動(dòng)態(tài)庫(kù)**libsqlite3.0.tbd

//聲明全局的db
sqlite3 *db;
//創(chuàng)建數(shù)據(jù)庫(kù)并打開數(shù)據(jù)庫(kù)
    NSString *dbFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"my.db"];
    
    int result = sqlite3_open(dbFilePath.UTF8String, &_db);
    
    if(result == SQLITE_OK){
    //2.創(chuàng)建表 
        NSString *createTableSQL = @"create table if not exists t_studentInfo(studentNO integer primary             key,studentName text not null,studentAge integer not null default 1);";
        
        sqlite3_exec(_db, createTableSQL.UTF8String, NULL, NULL, &errmsg);
        if (errmsg==NULL) {
            NSLog(@"創(chuàng)建表成功");
        }else{
            NSLog(@"%s",errmsg);
        }
    }

/**
函數(shù)的參數(shù):
  參數(shù)1:數(shù)據(jù)庫(kù)的實(shí)例
  參數(shù)2:創(chuàng)表的SQL語(yǔ)句
  參數(shù)3:回調(diào),傳入NULL
  參數(shù)4:參數(shù)3回調(diào)函數(shù)的參數(shù)
  參數(shù)5:錯(cuò)誤信息
*/ 
//刪除表
 drop table if exists t_productInfo;
//插入語(yǔ)句
 insert into t_productInfo (productName,productPrice) values('茶葉蛋',100);
//修改語(yǔ)句
update t_productInfo set productName = '龍井',productPrice = 188.8 where productId = 3;
//刪除語(yǔ)句
delete from t_productInfo where productName = '全聚德烤鴨';
//查詢所有
select * from t_productInfo;
//查詢指定字段
select productName,productPrice from t_productInfo;
//統(tǒng)計(jì)查詢出來(lái)的結(jié)果個(gè)數(shù)
select  count(*) from t_productInfo;
 //查詢出來(lái)的最大的數(shù)
SELECT MAX(productprice) FROM t_productInfo;
//根據(jù)條件查詢
SELECT productName,productPrice from t_productInfo where productId > 10 OR productPrice >100;

select * from t_productInfo where productId < 5 and productPrice > 50;
//模糊查詢
select * from t_productInfo where productName like '%字符%';
//對(duì)查詢結(jié)果排序
//從小到大
select * from t_productInfo where productPrice > 10 order by productPrice desc;
//從大到小
select * from t_productInfo where productPrice > 10 order by productPrice asc,productId desc;
//分頁(yè)
select * from t_productInfo where productPrice > 1 order by productPrice desc limit 10,5
  • 稍微了解一些SQLite原生的都會(huì)對(duì)它的語(yǔ)句及函數(shù)感到痛心疾首!看到上面的操作,是不是感到很繁瑣?別急,下面就是福利

第三方框架FMDB的使用

FMDB是目前OC處理數(shù)據(jù)庫(kù)的最好用的第三方,沒(méi)有之一。以下是對(duì)它的用法的簡(jiǎn)單介紹。

****1.****對(duì)單線程的操作

  • 對(duì)單線程的操作,在FMDB中只需要用到類FMDatabase;如果是針對(duì)模型操作的話,可以參考一下代碼。
//創(chuàng)建學(xué)生的數(shù)據(jù)模型
//姓名
@property (nonatomic, copy) NSString *name;
//年齡
@property (nonatomic, assign) int age;
//創(chuàng)建處理數(shù)據(jù)庫(kù)操作的工具類,聲明一個(gè)簡(jiǎn)單的插入類方法
+ (void)insertStudent:(XLStudent *)student;

//在.m文件中要注意,因?yàn)樗嗅槍?duì)數(shù)據(jù)庫(kù)的操作都需要一個(gè)數(shù)據(jù)庫(kù)的實(shí)例,所以!需要?jiǎng)?chuàng)建一個(gè)數(shù)據(jù)庫(kù)的實(shí)例。在案例中我聲明了一個(gè)全局的數(shù)據(jù)操作實(shí)例

FMDatabase *_db;

//之所以寫在initialize類方法中,是因?yàn)樗械念惍?dāng)且僅當(dāng)該類第一次使用的時(shí)候才會(huì)被執(zhí)行,而且只會(huì)被執(zhí)行一次。

+ (void)initialize{

    NSString *dbFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"student.db"];

    _db = [FMDatabase databaseWithPath:dbFilePath];
    
    //2.打開數(shù)據(jù)庫(kù),這樣才能將沙盒document中的student.db 讀到我們內(nèi)存中來(lái)操作
    BOOL result = [_db open];
    if (result) {
        //3.創(chuàng)建表,參數(shù)就是SQL
        BOOL result2 = [_db executeUpdate:@"create table if not exists t_student(studentNO integer primary key,studentName text not null,studentAge integer not null default 1);"];
        if (result2) {
            NSLog(@"創(chuàng)建表成功!");
        }
    }else{
        NSLog(@"創(chuàng)建并且打開數(shù)據(jù)庫(kù)失敗");
    }
}

//實(shí)現(xiàn).h文件中聲明的插入方法
+ (void)insertStudent:(XLStudent *)student{
   BOOL insertResult = [_db executeUpdateWithFormat:@"insert into t_student (studentName,studentAge) values(%@,%d);",student.name,student.age];
    
    if (insertResult) {
        NSLog(@"插入成功!");
    }
}

//準(zhǔn)備好了數(shù)據(jù)模型和數(shù)據(jù)庫(kù)管理的工具類,下面的代碼是在主控制器中實(shí)現(xiàn)的
- (void)insert{
    XLStudent *student = [[XLStudent alloc] init];
    student.name = @"小明";
    student.age = 18;
    
    //
    [XLStudentDBTool insertStudent:student];
}

****2.****對(duì)多線程的操作

  • 下面是對(duì)以上代碼針對(duì)多線程操作進(jìn)行的更改
  • 需要用到的類是FMDatabase、FMDatabaseQueue(該類就是多編程操作才使用到的)
  • 需要新創(chuàng)建一個(gè)類繼承自FMDB的FMDatabaseQueue類,以方便使用在創(chuàng)建單例時(shí)使用。
截圖.png
//創(chuàng)建一個(gè)類繼承自FMDatabaseQueue,并聲明一個(gè)單例的方法是為了拿到FMDatabaseQueue內(nèi)部幫我們定義的一個(gè)操作數(shù)據(jù)庫(kù)的實(shí)例db。因?yàn)樗械臄?shù)據(jù)庫(kù)操作都離不開數(shù)據(jù)庫(kù)的實(shí)例!
+ (instancetype)sharedXLBaseQueue {
    
    static XLStudentBaseQueue *_instanceType;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //創(chuàng)建一個(gè)操作數(shù)據(jù)庫(kù)的實(shí)例
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"student.db"];
        //創(chuàng)建數(shù)據(jù)庫(kù)并打開
        _instanceType = [self databaseQueueWithPath:filePath];
    });
    return _instanceType;
}
//在XLStudentDBTool中拿到數(shù)據(jù)庫(kù)操作的實(shí)例,并執(zhí)行插入操作
+ (void)initialize {
    //根據(jù)單例拿到實(shí)例
    [[XLStudentBaseQueue sharedXLBaseQueue]inDatabase:^(FMDatabase *db) {
        BOOL result = [db executeUpdate:@"create table if not exists t_studentInfo(studentNO integer primary key,studentName text not null,studentAge integer not null default 1);"];
        if (result) {
            NSLog(@"創(chuàng)建成功");
        }
    }];

}

//在表中插入數(shù)據(jù)模型
+ (void)insertStudent:(XLStudent *)student {
    [[XLStudentBaseQueue sharedXLBaseQueue]inDatabase:^(FMDatabase *db) {
        BOOL result = [db executeUpdateWithFormat:@"insert into t_studentInfo (studentName,studentAge) values(%@,%d);",student.name,student.age];
        
        if (result) {
            NSLog(@"插入成功");
        }
        
    }];
    
}
//在viewController中異步執(zhí)行一下操作,插入數(shù)據(jù)模型
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //異步執(zhí)行插入操作
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        XLStudent *xiaoming = [[XLStudent alloc]init];
        
        xiaoming.name = @"小明";
        xiaoming.age = 10;
        
        [XLStudentDBTool insertStudent:xiaoming];
        
        NSLog(@"%@",[NSThread currentThread]);
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        XLStudent *xiaohong = [[XLStudent alloc]init];
        
        xiaohong.name = @"小紅";
        xiaohong.age = 12;
        
        [XLStudentDBTool insertStudent:xiaohong];
        
        NSLog(@"%@",[NSThread currentThread]);
    });
    
}

總結(jié)肯定不夠全面,還請(qǐng)多指教!

最后編輯于
?著作權(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)容