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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章