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类,以方便使用在创建单例时使用。

《SQLite及FMDB框架使用简介》 截图.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]);
    });
    
}

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

    原文作者:迷路的安然和无恙
    原文地址: https://www.jianshu.com/p/6c2ec0f7f724
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞