美文网首页
FMDB二次封装版

FMDB二次封装版

作者: Gzook | 来源:发表于2016-07-15 11:19 被阅读491次
MVC

在Model中创建BLL和DAL

  • BLL--业务逻辑层
  • DAL--数据访问层

对于数据的处理全放入数据访问层DAL,业务逻辑层BLL只是对方法的调用,而在主函数中是业务逻辑层BLL的方法的调用。
BLL相当于是主管,让DAL实际去实现数据的处理

利用FMDB来进行数据的存储封装方法

  • 引入sqlite3的框架
  • 把FMDB的文件作为第三方copy进来
  • 对FMDB进行二次封装fmdbHelper
#import <Foundation/Foundation.h>
#import "FMDB.h"

@interface FmdbHelper : NSObject

@property (nonatomic, strong) FMDatabase *db;

//单例的类方法
+(instancetype)fmdbHelper;

//执行更新(除了查询以外的方法)
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;

//查询
-(void)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)
arguments andReslutBlock:(void(^)(FMResultSet *set))block;

@end

#import "FmdbHelper.h"

@implementation FmdbHelper

//单例的类方法
+(instancetype)fmdbHelper{
    static FmdbHelper *instance;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [[FmdbHelper alloc] init];
        
        //db属性初始化
        //数据库文件的路径
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString *dbPath = [documentPath stringByAppendingPath
Component:@"temp.db"];
        NSLog(@"dbPath %@", dbPath);
        //初始化对象
        instance.db = [[FMDatabase alloc] initWithPath:dbPath];
    });
    return instance;
}

//执行更新(除了查询以外的方法)
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)
arguments{
    //打开数据库
    if ([_db open]) {
        //执行更新
        BOOL res = [_db executeUpdate:sql withArgumentsInArray:
arguments];
        //关闭数据库
        [_db close];
        return res;
    }
    return NO;
}

//查询
-(void)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)
arguments andReslutBlock:(void(^)(FMResultSet *set))block{
    //打开数据库
    if ([_db open]) {
        //执行查询
        FMResultSet *set = [_db executeQuery:sql withArgumentsInArray:
arguments];
        //遍历结果
        block(set);
        //关闭数据库
        [_db close];
    }
}

@end
  • 在DAL中进行数据的操作
  • 在DAL中要先创建sql语句
  • 执行sql语句

相关文章

网友评论

      本文标题:FMDB二次封装版

      本文链接:https://www.haomeiwen.com/subject/acjyjttx.html