FMDatabase 的使用方法



#define myTable @"myTables" 

#define name @"name"
#define age @"age"
#define pic @"pic"
@interface FMDataHelper ()

@property (nonatomic, strong)FMDatabase *db;
@end



***
1.数据库路径

***

- (NSString *)getTablePath{
    NSArray *docuPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    return [[docuPaths firstObject] stringByAppendingPathComponent:myTable];
}

***

2.创建表

****


- (void)createTableData{
    self.db = [FMDatabase databaseWithPath:[self getTablePath]];
    
    NSLog(@"dataBase_path  =====  %@",self.db.databasePath);

    if ([self.db open]) {
        NSString *sqrStr = [NSString stringWithFormat:@"create table if not exists %@ (%@ text, %@ integer, %@ blob)",myTable,name,age, pic ];
        
        BOOL results = [self.db executeUpdate:sqrStr];
        if (results) {
            NSLog(@"创建成功");
        }
        else{
            NSLog(@"创建失败");
        }
        [self.db close];
    }
    
}

***

3.插入数据

***

-(void)insertDataWithName:(NSString *)nameValue ageValue:(NSInteger)ageValue picValue:(NSData *)picValue{
//    [self.db beginTransaction];
    if ([self.db open]) {

    [_db beginTransaction];//开启事物()

        NSString *sqrStr = [NSString stringWithFormat:@"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ? ,?)",myTable,name,age,pic];
        BOOL results =  [self.db executeUpdate:sqrStr,nameValue,[NSNumber numberWithInteger:ageValue],picValue];
        if (results) {
            
            NSLog(@"插入成功");
            
        }
        else{
            
            NSLog(@"插入失败");
            
        }
        [self.db commit];   //提交事物

        [self.db close];
    }
}

***

4.查询数据库数据,保存到model中,存入数组中返回

***
-(NSMutableArray *)selectData{
    
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:1];

    if ([self.db open]) {

        NSString *sqrStr = [NSString stringWithFormat:@"select * from %@",myTable];
        FMResultSet *results = [self.db executeQuery:sqrStr];
        while ([results next]) {
            Model *model = [[Model alloc] init];
            model.nameValue = [results stringForColumn:name];
            model.picValue = [results dataForColumn:pic];
            model.ageValue = [results intForColumn:age];
            [arr addObject:model];
            
        }
//        [results close];
        [self.db close];
        
    }
    return arr;
    
}



你可能感兴趣的:(ios,FMDB)