数据库存取数据
static FMDatabase *_db;
(void)initialize
{
NSString cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// 拼接文件名
NSString filePath = [cachePath stringByAppendingPathComponent:@”onLineHome.sqlite”];
// 创建了一个数据库实例
_db = [FMDatabase databaseWithPath:filePath];// 打开数据库
if ([_db open]) {NSLog(@"打开成功");
}else{
NSLog(@"打开失败");
}
// 创建t_online_home表格
BOOL flag = [_db executeUpdate:@”create table if not exists t_online_home (id integer primary key autoincrement,tagid text,dict text);”];
if (flag) {NSLog(@"t_online_home 可用");
}else{
NSLog(@"t_online_home 创建失败");
}
}(void)saveWithOnlineVC:(NSDictionary )onlinevc withTagId:(NSNumber )tagid{
BOOL isHaveRet = NO;
NSString sel = [NSString stringWithFormat:@”select from t_online_home where tagid = ‘%@’;”,tagid];
FMResultSet * set = [_db executeQuery:sel];
while ([set next]) {isHaveRet = YES; break;
}
NSString sql = nil;
NSString json = [YYUtil json2String:onlinevc];
if (isHaveRet) {sql = [NSString stringWithFormat:@"UPDATE t_online_home SET dict = '%@' WHERE tagid = '%@';", json,tagid];
}else{
sql = [NSString stringWithFormat:@"insert into t_online_home (tagid,dict) values('%@','%@')",tagid ,json];
}
BOOL ret = [_db executeUpdate:sql];if (ret) {
NSLog(@"update successed");
}else{
NSLog(@"%@", [_db lastErrorMessage]);
}
}
- (NSDictionary )onlineVCWithTagId:(NSNumber )tagid{
// 进入程序第一次获取的查询语句
NSString sql = [NSString stringWithFormat:@”select from t_online_home where tagid = ‘%@’;”,tagid];
FMResultSet *set = [_db executeQuery:sql];
while ([set next]) {
}NSString *json = [set stringForColumn:@"dict"]; NSDictionary *dict = [YYUtil string2Json:json]; NSLog(@"%@",dict); return dict;
return nil;
}