数据持久化存储:FMDB的使用

FMDB简介:一种第三方开源库,其实就是对SQLite的API进行了封装,在加上面向对象的思想,就不必再用繁琐的C语言API函数了,这要比直接使用SQLite更加的方便。

FMDB优点:使用起来更加面向对象,变得简洁,使用方便;

                     对比苹果自带的CoreData框架,更加轻量级,更加灵活;

                     提供了多线程安全,有效的防止数据混乱,原来的SQLite不是线程安全的。

FMDB缺点:因为是OC语言封装的,所以失去了SQLite原来的跨平台性。

FMDB主要有三个类:1.FMDatabase:一个单一的SQLite数据库,用来执行SQL语句

                                    2.FMResultSet:执行查询一个FMDatabase结果集合。

                                    3.FMDatabaseQueue:在多个线程来执行和更新时会使用这个类。


使用步骤:1.导入FMDB:可以直接在github上下载源码,然后带入工程https://github.com/ccgus/fmdb;也可以用cocoapods导入,进入vim podfile  , pod 'FMDB'

                  2.在项目中添加依赖库libsqlite3.dylib

                  3.#import "FMDatabase.h"

接下来创建数据库:

                  创建数据库使用到的是FMDatabase的类方法:1. 如果该路径下已经存在该数据库,直接获取该数据库; 2. 如果不存在就创建一个新的数据库; 3. 如果传@"",会在临     时目录创建一个空的数据库,当数据库关闭时,数据库文件也被删除; 4. 如果传nil,会在内存中临时创建一个空的数据库,当数据库关闭时,数据库文件也被删除;

NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
NSString *filePath = [path stringByAppendingPathComponent:@"FMDB.db"];
FMDatabase *database = [FMDatabase databaseWithPath:filePath];

这里要注意的是,在哪里使用数据库就在哪里打开,使用完后要关闭:

[database open];

[database close];

执行跟新的SQL语句用到的常用方法:

/* 执行更新的SQL语句,字符串里面的"?",依次用后面的参数替代,必须是对象,不能是int等基本类型 */
- (BOOL)executeUpdate:(NSString *)sql,... ;
/* 执行更新的SQL语句,可以使用字符串的格式化进行构建SQL语句 */
- (BOOL)executeUpdateWithFormat:(NSString*)format,... ;
/* 执行更新的SQL语句,字符串中有"?",依次用arguments的元素替代 */
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;

下面的4种使用等价:

/* 1. 直接使用完整的SQL更新语句 */
[database executeUpdate:@"insert into mytable(num,name,sex) values(0,'liuting','m');"];

NSString *sql = @"insert into mytable(num,name,sex) values(?,?,?);";
/* 2. 使用不完整的SQL更新语句,里面含有待定字符串"?",需要后面的参数进行替代 */
[database executeUpdate:sql,@0,@"liuting",@"m"];
/* 3. 使用不完整的SQL更新语句,里面含有待定字符串"?",需要数组参数里面的参数进行替代 */
[database executeUpdate:sql
   withArgumentsInArray:@[@0,@"liuting",@"m"]];

/* 4. SQL语句字符串可以使用字符串格式化,这种我们应该比较熟悉 */
[database executeUpdateWithFormat:@"insert into mytable(num,name,sex) values(%d,%@,%@);",0,@"liuting","m"];

使用实例:

- (BOOL)createTable {
    NSString *sqlStr = @"create table mytable(num integer,name varchar(7),sex char(1),primary key(num));";
    BOOL res = [_database executeUpdate:sqlStr];
    if (!res) {
        NSLog(@"error when creating database table");
        [_database close];
    }
    return res;
}

执行查询的SQL语句常用方法

/* 执行查询SQL语句,返回FMResultSet查询结果 */
- (FMResultSet *)executeQuery:(NSString*)sql, ... ;
- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... ;
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;

处理结果FMResultSet的常用方法:

/* 获取下一个记录 */
- (BOOL)next;
/* 获取记录有多少列 */
- (int)columnCount;
/* 通过列名得到列序号,通过列序号得到列名 */
- (int)columnIndexForName:(NSString *)columnName;
- (NSString *)columnNameForIndex:(int)columnIdx;
/* 获取存储的整形值 */
- (int)intForColumn:(NSString *)columnName;
- (int)intForColumnIndex:(int)columnIdx;
/* 获取存储的长整形值 */
- (long)longForColumn:(NSString *)columnName;
- (long)longForColumnIndex:(int)columnIdx;
/* 获取存储的布尔值 */
- (BOOL)boolForColumn:(NSString *)columnName;
- (BOOL)boolForColumnIndex:(int)columnIdx;
/* 获取存储的浮点值 */
- (double)doubleForColumn:(NSString *)columnName;
- (double)doubleForColumnIndex:(int)columnIdx;
/* 获取存储的字符串 */
- (NSString *)stringForColumn:(NSString *)columnName;
- (NSString *)stringForColumnIndex:(int)columnIdx;
/* 获取存储的日期数据 */
- (NSDate *)dateForColumn:(NSString *)columnName;
- (NSDate *)dateForColumnIndex:(int)columnIdx;
/* 获取存储的二进制数据 */
- (NSData *)dataForColumn:(NSString *)columnName;
- (NSData *)dataForColumnIndex:(int)columnIdx;
/* 获取存储的UTF8格式的C语言字符串 */
- (const unsigned cahr *)UTF8StringForColumnName:(NSString *)columnName;
- (const unsigned cahr *)UTF8StringForColumnIndex:(int)columnIdx;
/* 获取存储的对象,只能是NSNumber、NSString、NSData、NSNull */
- (id)objectForColumnName:(NSString *)columnName;
- (id)objectForColumnIndex:(int)columnIdx;

使用实例:

- (NSArray *)getResultFromDatabase{
    //执行查询SQL语句,返回查询结果
    FMResultSet *result = [_database executeQuery:@"select * from mytable"];
    NSMutableArray *array = [NSMutableArray array];
    //获取查询结果的下一个记录
    while ([result next]) {
        //根据字段名,获取记录的值,存储到字典中
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        int num  = [result intForColumn:@"num"];
        NSString *name = [result stringForColumn:@"name"];
        NSString *sex  = [result stringForColumn:@"sex"];
        dict[@"num"] = @(num);
        dict[@"name"] = name;
        dict[@"sex"] = sex;
        //把字典添加进数组中
        [array addObject:dict];
    }
    return array;
}

多线程安全FMDatabaseQueue

FMDatabase这个类是线程不安全的,如果在多个线程同时使用一个FMDatabase实例,会造成数据混乱问题。
为了保证线程安全,FMDB提供方便快捷的FMDatabaseQueue类,要使用这个类,需要#import导入头文件"FMDatabaseQueue.h"FMDatabaseQueue类的操作很多都和FMDatabase很相似

创建

NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
NSString *filePath = [path stringByAppendingPathComponent:@"FMDB.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];

操作数据库

[queue inDatabase:^(FMDatabase*db) {
    //FMDatabase数据库操作
}];

使用实例

[queue inDatabase:^(FMDatabase*db) {
    //插入记录到表中
    NSString *sqlStr = @"insert into mytable(num,name,sex) values(4,'xiaoming','m');";
    BOOL result = [db executeUpdate:sqlStr];
    if (!result) {
        NSLog(@"error when insert into database table");
        [db close];
    }
}];

事务

事务,是指作为单个逻辑工作单元执行的一系列操作,要么完整地执行,要么完全地不执行。

想象一个场景,比如你要更新数据库的大量数据,我们需要确保所有的数据更新成功,才采取这种更新方案,如果在更新期间出现错误,就不能采取这种更新方案了,如果我们不使用事务,我们的更新操作直接对每个记录生效,万一遇到更新错误,已经更新的数据怎么办?难道我们要一个一个去找出来修改回来吗?怎么知道原来的数据是怎么样的呢?这个时候就需要使用事务实现。
之所以将事务放到FMDB中去说并不是因为只有FMDB才支持事务,而是因为FMDB将其封装成了几个方法来调用,不用自己写对应的SQL而已。

SQLite进行事务的SQL语句:

只要在执行SQL语句前加上以下的SQL语句,就可以使用事务功能了:
开启事务的SQL语句,"begin transaction;"
进行提交的SQL语句,"commit transaction;"
进行回滚的SQL语句,"rollback transaction;"

只有事务提交了,开启事务期间的操作才会生效

FMDatabase使用事务的方法

//事务
-(void)transaction {
    // 开启事务
    [self.database beginTransaction];
    BOOL isRollBack = NO;
    @try {
        for (int i = 0; i<500; i++) {
            NSNumber *num = @(i+1);
            NSString *name = [[NSString alloc] initWithFormat:@"student_%d",i];
            NSString *sex = (i%2==0)?@"f":@"m";
            NSString *sql = @"insert into mytable(num,name,sex) values(?,?,?);";
            BOOL result = [database executeUpdate:sql,num,name,sex];
            if ( !result ) {
                NSLog(@"插入失败!");
                return;
            }
        }
    }
    @catch (NSException *exception) {
        isRollBack = YES;
        // 事务回退
        [self.database rollback];
    }
    @finally {
        if (!isRollBack) {
            //事务提交
            [self.database commit];
        }
    }
}

FMDatabaseQueue使用事务的方法

//多线程事务
- (void)transactionByQueue {
    //开启事务
    [self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
         for (int i = 0; i<500; i++) {
            NSNumber *num = @(i+1);
            NSString *name = [[NSString alloc] initWithFormat:@"student_%d",i];
            NSString *sex = (i%2==0)?@"f":@"m";
            NSString *sql = @"insert into mytable(num,name,sex) values(?,?,?);";
            BOOL result = [db executeUpdate:sql,num,name,sex];
            if ( !result ) {
                //当最后*rollback的值为YES的时候,事务回退,如果最后*rollback为NO,事务提交
                *rollback = YES;
                 return;
            }
        }
     }];
}

FMDB的类说明文档http://ccgus.github.io/fmdb/html/index.html


结合项目:

1.创建一个数据model:Person

.h

#import <Foundation/Foundation.h>

@interface Person : NSObject
@property(nonatomic)int age;
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *gender;
@property(nonatomic,copy)NSString *province;
@end

2.创建一个数据库管理类


.h

#import <Foundation/Foundation.h>
#import "FMDataBase.h"
#import "Person.h"
@interface DataBase : NSObject
//单例
+(instancetype)sharedDBManager;

//增
-(void)insertModel:(id)personModel;
//删除
-(void)deleteModelByName:(NSString *)name;
//修改
-(void)updateModel:(Person *)personModel;
//查询
-(NSMutableArray *)fetchAll;
@end


.m

#import "DataBase.h"

static DataBase *_dataBase = nil;

@interface DataBase ()<NSCopying>{
    FMDatabase *_dbManager;
}

@end

@implementation DataBase
//GCD 单例
//这个方法服务于alloc 无论外界调用多少次alloc 返回的都是一个内存空间
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _dataBase = [super allocWithZone:zone];
    });
    return _dataBase;
}
//共享方法,便于外界调用
//但是避免不了外界init多次,所以要带入init,这里的alloc会调用上面的方法
+(instancetype)sharedDBManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _dataBase = [[DataBase alloc]init];
    });
    return _dataBase;
}
//这个方法避免外界实现copy方法(这里要遵循NSCopying协议)
-(id)copyWithZone:(NSZone *)zone{
    return _dataBase;
}

-(id)init{
    if (self = [super init]) {
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        //数据库路径
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"preson.db"];
        NSLog(@"地址:%@",filePath);
        //创建数据库
        _dbManager = [[FMDatabase alloc]initWithPath:filePath];

        if ([_dbManager open]) {
            NSLog(@"数据库打开成功!");
            //创建数据表格
            [self createDataTable];
        }else{
            NSLog(@"数据库打开失败%@",_dbManager.lastErrorMessage);
        }
        [_dbManager close];
        
    }
    return self;
}
-(void)createDataTable{
    NSString *sql = @"create table if not exists personInfo(personName Varch(1024),personGender Varch(1024),personAge integer,personProvince Varch(1024))";
    BOOL isSuccess = [_dbManager executeUpdate:sql];
    if (!isSuccess) {
        NSLog(@"创建表失败:%@",_dbManager.lastErrorMessage);
    }
}
//增添数据
-(void)insertModel:(id)personModel{
    [_dbManager open];
    Person *person = (Person *)personModel;
    NSString *sql = @"insert into personInfo(personName,personGender,personAge,personProvince)values(?,?,?,?)";
    BOOL isSuccess = [_dbManager executeUpdate:sql,person.name,person.gender,@(person.age),person.province];
    if (!isSuccess) {
        NSLog(@"增加数据失败:%@",_dbManager.lastErrorMessage);
    }
    [_dbManager close];
}
//删除数据
-(void)deleteModelByName:(NSString *)name{
    [_dbManager open];
    NSString *sql = @"delete from personInfo where personName = ?";
    BOOL isSuccess = [_dbManager executeUpdate:sql,name];
    if (!isSuccess) {
        NSLog(@"删除数据失败:%@",_dbManager.lastErrorMessage);
    }
    [_dbManager close];
}
//修改数据
-(void)updateModel:(Person *)personModel{
    [_dbManager open];
    NSString *sql = @"update personInfo set personGender = ?, personAge = ? ,personProvince = ? where personName = ?";
    BOOL isSuccess = [_dbManager executeUpdate:sql,personModel.age,personModel.age,personModel.province,personModel.name];
    if (!isSuccess) {
        NSLog(@"更新数据失败%@",_dbManager.lastErrorMessage);
    }
    [_dbManager close];
}
-(NSMutableArray *)fetchAll{
    [_dbManager open];
    NSMutableArray *arr = [NSMutableArray array];
    NSString *sql = @"select * from personInfo";
    FMResultSet *rest = [_dbManager executeQuery:sql];
    while ([rest next]) {
        Person *person = [[Person alloc]init];
        person.name = [rest stringForColumn:@"personName"];
        person.gender = [rest stringForColumn:@"personGender"];
        person.age = [rest intForColumn:@"personAge"];
        person.province = [rest stringForColumn:@"personProvince"];
        [arr addObject:person];
    }
    [_dbManager close];
    return arr;
}
@end



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值