SYCacheManager缓存数据操作

SYCacheManager使用FMDB、LKDB进行二次封装,缓存数据。

SYCacheManager缓存数据操作_第1张图片
FMDB使用效果图
SYCacheManager缓存数据操作_第2张图片
LKDBHelper使用效果图

FMDB的基本使用
使用FMDatabase操作数据,使用时,必须保证如下三点:
(1)已创建数据库
(2)操作前,必须打开数据库
(3)操作后,必须关闭数据库
数据库存储路径

- (NSString *)dataPath
{
    if (_dataPath == nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *documentDirectory = [paths objectAtIndex:0];
        _dataPath = [documentDirectory stringByAppendingPathComponent:@"cache.db"];
        
        NSLog(@"_dataPath = %@", _dataPath);
    }
    return _dataPath;
}

FMDatabase实例化,并创建数据库

- (FMDatabase *)dataBase
{
    if (_dataBase == nil)
    {
        _dataBase = [FMDatabase databaseWithPath:self.dataPath];
    }
    return _dataBase;
}
  • 创建表
if ([self.dataBase open])
{
            NSString *createTabel = @"CREATE TABLE if not exists CompanyTable (departmentId text PRIMARY KEY,departmentName text,departmentStatus text)";
            BOOL isResult = [self. dataBase executeUpdate:createTabel];
            NSLog(@"createTabel = %@", (isResult ? @"success" : @"error"));
            [self.dataBase close];
}
  • 删除表
if ([self.dataBase open])
{
            NSString *deleteTabel = @"DROP TABLE CompanyTable";
            BOOL isResult = [self. dataBase executeUpdate:deleteTabel];
            NSLog(@"deleteTabel = %@", (isResult ? @"success" : @"error"));
            [self.dataBase close];
}
  • 保存数据
if ([self.dataBase open])
{
            NSString *saveData = @"INSERT INTO CompanyTable (departmentId, departmentName, departmentStatus) VALUES (?,?,?)";
            BOOL isResult = [self. dataBase executeUpdate:saveData, @"168", @"互联网部门", @"禁用"];
            NSLog(@"saveData = %@", (isResult ? @"success" : @"error"));
            [self.dataBase close];
}
  • 删除数据
if ([self.dataBase open])
{
            NSString *deleteData = @"DELETE FROM CompanyTable";
            BOOL isResult = [self. dataBase executeUpdate:deleteData];
            NSLog(@"deleteData = %@", (isResult ? @"success" : @"error"));
            [self.dataBase close];
}
  • 修改数据
if ([self.dataBase open])
{
            NSString *modifyData = @"UPDATE CompanyTable set departmentStatus = ? where departmentName = ?";
            BOOL isResult = [self. dataBase executeUpdate:modifyData, @"启用", @"互联网部门"];
            NSLog(@"modifyData = %@", (isResult ? @"success" : @"error"));
            [self.dataBase close];
}
  • 读取数据
if ([self.dataBase open])
{
            NSString *readData = @"SELECT * FROM CompanyTable WHERE departmentName = ?";
            FMResultSet *result = [self. dataBase executeQuery:readData, @"互联网部门"];
            // 读取全部数据
            while ([result next])
            {
                NSString *idStr = [result stringForColumn:@"departmentId"];
                NSString *nameStr = [result stringForColumn:@"departmentName"];
                NSString *statusStr = [result stringForColumn:@"departmentStatus"];
                
                NSLog(@"查找数据成功。\nid = %@, name = %@, status = %@", idStr, nameStr, statusStr);
            }
            [self.dataBase close];
}
// 读取单条数据
if ([result next])
{
             NSString *idStr = [result stringForColumn:@"departmentId"];
             NSString *nameStr = [result stringForColumn:@"departmentName"];
             NSString *statusStr = [result stringForColumn:@"departmentStatus"];
                
             NSLog(@"查找数据成功。\nid = %@, name = %@, status = %@", idStr, nameStr, statusStr);
}

执行语句使用的四种等价情况,使用更新语句示例

  • 直接使用完整的SQL
NSString *sqlUpate = @"UPDATE CompanyTable(departmentStatus) values('启用')";
[self.dataBase executeUpdate:sqlUpate];
  • 使用不完整的SQL,里面含有待定字符串"?",需要后面的参数进行替代
NSString *sqlUpate = @"UPDATE CompanyTable set departmentStatus = ? where departmentName = ?";
[self.dataBase executeUpdate:sqlUpate, @"启用", @"互联网部门"];
  • 使用不完整的SQL,里面含有待定字符串"?",需要数组参数里面的参数进行替代
NSString *sqlUpate = @"UPDATE CompanyTableUPDATE CompanyTable(departmentStatus) values(?)";
[self.dataBase executeUpdate:sqlUpate withArgumentsInArray:@[@"启用"]];
  • SQL语句字符串可以使用字符串格式化,这种我们应该比较熟悉
NSString *sqlUpate = @"UPDATE CompanyTable(departmentName) values(%@)";
[self.dataBase executeUpdateWithFormat:sqlUpate, @"启用"];

LKDB的基本使用
通常使用时,采用单例设计模式进行使用。
数据库存储路径:只需要设置数据库名称即可,实例化时已实现创建路径方法。
实例化

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.dataHelper = [[LKDBHelper alloc] initWithDBName:@"LKDB.db"];
    }    
    return self;
}

单例

/// 单例
+ (SYCacheManager *)shareCache
{
    static SYCacheManager *sharedManager;
    static dispatch_once_t onceToken;    
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
        assert(sharedManager != nil);
    });    
    return sharedManager;
}
  • 创建表
- (BOOL)newTableWithModel:(Class)class
{
    BOOL isResult = NO;
    if ([self.dataHelper isExistsWithTableName:NSStringFromClass(class) where:nil])
    {
        isResult = YES;
        NSLog(@"newTableWithModel = 已存在");
    }
    else
    {
        isResult = [self.dataHelper createTableWithModelClass:class];
    }
    NSLog(@"newTableWithModel = %@", (isResult ? @"success" : @"error"));
    return isResult;
}
  • 删除表
    • 删除所有表
    • 删除指定表
- (void)deleteAllTableModel
{
    [self.dataHelper dropAllTable];
}

- (BOOL)deleteTableWithModel:(Class)class
{
    BOOL isResult = [self.dataHelper dropTableWithClass:class];
    NSLog(@"deleteTableWithModel = %@", (isResult ? @"success" : @"error"));
    return isResult;
}
  • 保存数据
- (BOOL)saveModel:(id)model
{
    BOOL isResult = NO;
    if ([self.dataHelper isExistsModel:model])
    {
        // 已存在时,先删除,且删除成功再保存
        if ([self deleteModel:model])
        {
            isResult = [self.dataHelper insertWhenNotExists:model];
        }
    }
    else
    {
        // 不存在时,直接删除
        isResult = [self.dataHelper insertWhenNotExists:model];
    }
    NSLog(@"saveModel = %@", (isResult ? @"success" : @"error"));
    return isResult;
}
  • 删除数据
    • 删除数据
    • 删除指定条件的数据
- (BOOL)deleteModel:(id)model
{
    BOOL isResult = [self.dataHelper deleteToDB:model];
    NSLog(@"isResult = %@", (isResult ? @"success" : @"error"));
    return isResult;
}

- (BOOL)deleteModel:(Class)class where:(id)where
{
    BOOL isResult = [self.dataHelper deleteWithClass:class where:where];
    NSLog(@"isResult = %@", (isResult ? @"success" : @"error"));
    return isResult;
}
  • 修改数据
    • 修改数据
    • 修改指定条件的数据
- (BOOL)updateModel:(id)model
{
    BOOL isResult = [self.dataHelper updateToDB:model where:nil];
    NSLog(@"updateModel = %@", (isResult ? @"success" : @"error"));
    return isResult;
}

- (BOOL)updateModel:(Class)class value:(NSString *)value where:(id)where
{
    BOOL isResult = [self.dataHelper updateToDB:class set:value where:where];
    NSLog(@"updateModel = %@", (isResult ? @"success" : @"error"));
    return isResult;
}
  • 查找数据
- (NSArray *)readModel:(Class)class where:(id)where
{
    //  根据 and 条件 查询所有数据 NSString *conditions = @"age = 23 and name = '张三1'";
    //  根据 字典条件,查询所有数据 NSDictionary *conditions1 = @{@"age" : @23, @"name" : @"张三1"};
    //  根据 or 条件,查询所有数据 NSString *conditions2 = @"age = 23 or ID = 5";
    //  根据 in 条件,查询所有数据 NSString *conditions3 = @"age in (23, 24)";
    //  根据 字典 in 条件,查询所有数据 NSDictionary *conditions4 = @{@"age" : @[@23, @24]};
    //  查询符合条件的数据有多少条 NSString *conditions5 = @"age = 23 and name = '张三1'";
    
    NSArray *array = [self.dataHelper search:class column:nil where:where orderBy:nil offset:0 count:0];
    return array;
}

你可能感兴趣的:(SYCacheManager缓存数据操作)