SQLite及FMDB框架使用简介

SQLite作为轻量级的嵌入式数据库,在移动端已经普遍使用。其实数据库内部的样子,可以把它理解成Excel表格,至于数据结构嘛.......囧
数据库可以分为两类:
(1)关系型数据库
(2)对象型数据库
关系型的是目前使用的主流

其他类型数据库的介绍:Oracle、MySQL、SQL Server

Navicat
是一款数据库的管理软件,支持大部分主流数据库。

SQLite的语法及基本使用**
在xCode工程中首先要导入动态库**libsqlite3.0.tbd

//声明全局的db
sqlite3 *db;
//创建数据库并打开数据库
    NSString *dbFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"my.db"];
    
    int result = sqlite3_open(dbFilePath.UTF8String, &_db);
    
    if(result == SQLITE_OK){
    //2.创建表 
        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(@"创建表成功");
        }else{
            NSLog(@"%s",errmsg);
        }
    }

/**
函数的参数:
  参数1:数据库的实例
  参数2:创表的SQL语句
  参数3:回调,传入NULL
  参数4:参数3回调函数的参数
  参数5:错误信息
*/ 
//删除表
 drop table if exists t_productInfo;
//插入语句
 insert into t_productInfo (productName,productPrice) values('茶叶蛋',100);
//修改语句
update t_productInfo set productName = '龙井',productPrice = 188.8 where productId = 3;
//删除语句
delete from t_productInfo where productName = '全聚德烤鸭';
//查询所有
select * from t_productInfo;
//查询指定字段
select productName,productPrice from t_productInfo;
//统计查询出来的结果个数
select  count(*) from t_productInfo;
 //查询出来的最大的数
SELECT MAX(productprice) FROM t_productInfo;
//根据条件查询
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 '%字符%';
//对查询结果排序
//从小到大
select * from t_productInfo where productPrice > 10 order by productPrice desc;
//从大到小
select * from t_productInfo where productPrice > 10 order by productPrice asc,productId desc;
//分页
select * from t_productInfo where productPrice > 1 order by productPrice desc limit 10,5
  • 稍微了解一些SQLite原生的都会对它的语句及函数感到痛心疾首!看到上面的操作,是不是感到很繁琐?别急,下面就是福利

第三方框架FMDB的使用

FMDB是目前OC处理数据库的最好用的第三方,没有之一。以下是对它的用法的简单介绍。

****1.****对单线程的操作

  • 对单线程的操作,在FMDB中只需要用到类FMDatabase;如果是针对模型操作的话,可以参考一下代码。
//创建学生的数据模型
//姓名
@property (nonatomic, copy) NSString *name;
//年龄
@property (nonatomic, assign) int age;
//创建处理数据库操作的工具类,声明一个简单的插入类方法
+ (void)insertStudent:(XLStudent *)student;

//在.m文件中要注意,因为所有针对数据库的操作都需要一个数据库的实例,所以!需要创建一个数据库的实例。在案例中我声明了一个全局的数据操作实例

FMDatabase *_db;

//之所以写在initialize类方法中,是因为所有的类当且仅当该类第一次使用的时候才会被执行,而且只会被执行一次。

+ (void)initialize{

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

    _db = [FMDatabase databaseWithPath:dbFilePath];
    
    //2.打开数据库,这样才能将沙盒document中的student.db 读到我们内存中来操作
    BOOL result = [_db open];
    if (result) {
        //3.创建表,参数就是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(@"创建表成功!");
        }
    }else{
        NSLog(@"创建并且打开数据库失败");
    }
}

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

//准备好了数据模型和数据库管理的工具类,下面的代码是在主控制器中实现的
- (void)insert{
    XLStudent *student = [[XLStudent alloc] init];
    student.name = @"小明";
    student.age = 18;
    
    //
    [XLStudentDBTool insertStudent:student];
}

****2.****对多线程的操作

  • 下面是对以上代码针对多线程操作进行的更改
  • 需要用到的类是FMDatabase、FMDatabaseQueue(该类就是多编程操作才使用到的)
  • 需要新创建一个类继承自FMDB的FMDatabaseQueue类,以方便使用在创建单例时使用。
截图.png
//创建一个类继承自FMDatabaseQueue,并声明一个单例的方法是为了拿到FMDatabaseQueue内部帮我们定义的一个操作数据库的实例db。因为所有的数据库操作都离不开数据库的实例!
+ (instancetype)sharedXLBaseQueue {
    
    static XLStudentBaseQueue *_instanceType;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //创建一个操作数据库的实例
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"student.db"];
        //创建数据库并打开
        _instanceType = [self databaseQueueWithPath:filePath];
    });
    return _instanceType;
}
//在XLStudentDBTool中拿到数据库操作的实例,并执行插入操作
+ (void)initialize {
    //根据单例拿到实例
    [[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(@"创建成功");
        }
    }];

}

//在表中插入数据模型
+ (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中异步执行一下操作,插入数据模型
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //异步执行插入操作
    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]);
    });
    
}

总结肯定不够全面,还请多指教!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,809评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,189评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,290评论 0 359
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,399评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,425评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,116评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,710评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,629评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,155评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,261评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,399评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,068评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,758评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,252评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,381评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,747评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,402评论 2 358

推荐阅读更多精彩内容