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;
    
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值