FMDB基本使用

#import "PersonDBTool.h"
#import <FMDB.h>

@implementation PersonDBTool


static FMDatabase *_dataBase;

+ (void)initialize{
    //1.創建數據,並且打開/連接到沙盒中的數據庫
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"person.db"];
    
    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    //2.打開
    BOOL result = [_dataBase open];
    

    if(result){
        //3.創建表
        BOOL createTableResult = [_dataBase executeUpdate:@"create table if not exists t_person(id integer primary key,name text,age integer);"];
        
        if(createTableResult){
            NSLog(@"create Table ok!!!");
        }else{
            NSLog(@"error!!!");
        }
    }
}

#pragma mark - FMDB DML語句
+ (void)insertPerson:(Person *)person{
    [_dataBase executeUpdateWithFormat:@"insert into t_person(name,age) values(%@,%d) ;",person.name,person.age];
}

+ (void)updatePerson:(Person *)person{
    [_dataBase executeUpdateWithFormat:@"update t_person set age = %d where name = %@",person.age,person.name];
}

+ (void)deletePersonWithId:(int)personId{
    [_dataBase executeUpdateWithFormat:@"delete from t_person where id = %d",personId];
}

#pragma mark - DQL語句
+ (NSArray *)queryAllPerson{
    NSMutableArray *persons = [NSMutableArray array];
    
    FMResultSet *resultSet = [_dataBase executeQuery:@"select * from t_person"];
    
    while ([resultSet next]) {//遍歷到每一條記錄
        NSString *pname = [resultSet stringForColumn:@"name"];
        int age = [resultSet intForColumn:@"age"];
        
        Person *p = [[Person alloc] init];
        p.name = pname;
        p.age = age;
        
        [persons addObject:p];
    }
    
    return persons.copy;
}

+ (NSArray *)queryPersonWithKeyWord:(NSString *)keyWord{
    NSMutableArray *persons = [NSMutableArray array];

    FMResultSet *resultSet = [_dataBase executeQuery:[NSString stringWithFormat:@"select * from t_person where name like '%%%@%%';",keyWord]];
    
    while ([resultSet next]) {//遍歷到每一條記錄
        NSString *pname = [resultSet stringForColumn:@"name"];
        int age = [resultSet intForColumn:@"age"];
        
        Person *p = [[Person alloc] init];
        p.name = pname;
        p.age = age;
        
        [persons addObject:p];
    }
    
    return persons.copy;
}

@end

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