FMDB的使用

原创
2017/07/02 20:47
阅读数 91
-(BOOL)isExisted:(NSString*)name{
    [self openDB];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT name FROM t_wy Where name = '%@'",name];
    NSLog(@"existed - %@",sql);
    FMResultSet *set = [self.db executeQuery:sql];
    
    int count = 0;
    
    /*
        columnCount - 是字段个数
     
        注意,如果没有值,这个参数就是0
     
        也就是说,在调用next的前后,如果结果个数是0个,这个columnCount会在next指令后变为0
     */
    
    while ([set next]) {
        count++;
    }
    
    return  (count)?YES:NO;
    
}

-(void)UpDataToDataBase:(NSDictionary *)dict withName:(NSString*)name{
    [self openDB];
    // 存储的是二进制 ->  字典转二进制dataWithJSONObject
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    //实际c语言
    bool su = [self.db executeUpdate:@"UPDATE t_wy SET data = '?' WHERE name = '?'",data,name];
    
    if (su) {
        NSLog(@"更新正确");
    }else{
        NSLog(@"更新失败");
    }
}


-(void)SaveDataToDataBase:(NSDictionary *)dict withName:(NSString*)name;
{
    [self openDB];
    
    // 存储的是二进制 ->  字典转二进制dataWithJSONObject
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    //实际c语言
    bool su = [self.db executeUpdate:@"INSERT INTO t_wy(data,name) VALUES(?,?)",data,name];
    
    if (su) {
        NSLog(@"存储正确");
    }else{
        NSLog(@"存储失败");
    }
    
}

-(void)openDB
{
    if (self.db == nil) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = paths[0];
        path = [path stringByAppendingPathComponent:@"wy.sqlite"];
        
        self.db = [FMDatabase databaseWithPath:path];
        
        NSLog(@"path - %@",path);
        
        [self.db open];
        
        //直接创建表
        NSString *sql = @"CREATE TABLE IF NOT EXISTS t_wy (id INTEGER PRIMARY KEY AUTOINCREMENT,data blob,name text)";
        bool su =[self.db executeUpdate:sql];
        
        if (su) {
            NSLog(@"创建表成功");
        }else{
            NSLog(@"创建表失败");
        }
    }
}

-(NSDictionary *)LoadData:(NSString*)name
{
    [self openDB];
    NSString *sql =[NSString stringWithFormat:@"SELECT data FROM t_wy Where name ='%@'",name];
    
    FMResultSet *set = [self.db executeQuery:sql];
    
    NSMutableDictionary *dict_data;
    while ([set next]) {
        
        NSError *err;
        //dataForColumn
        
        id dict = [NSJSONSerialization JSONObjectWithData:[set dataForColumn:@"data"] options:NSJSONReadingMutableContainers error:&err];
        
        NSLog(@"result - %@",dict);
        NSLog(@"json-Error - %@",err.localizedDescription);
        
        dict_data=[NSMutableDictionary dictionaryWithDictionary:dict];
        
    }
    return dict_data;
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部