阅读 90

FMDB的使用

引入和创建文件

创建方法创建表,实现数据的CURD

初始化创建表

- (id)init{
    self = [super init];
    if (self) {
        NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *dbPath = [docuPath stringByAppendingPathComponent:@"user.db"];
        
        _db = [FMDatabase databaseWithPath:dbPath];
        
        [_db open];
        if (![_db open]) {
            NSLog(@"db open fail");
            return nil;
        }
        NSString *sql = @"create table if not exists t_user ('ID' INTEGER PRIMARY KEY AUTOINCREMENT,'account' TEXT NOT NULL, 'password' TEXT NOT NULL)";
        
        BOOL result = [_db executeUpdate:sql];
        if (result) {
           
        }
        [_db close];
    }
    return self;
}
复制代码

插入数据

- (void)insertUserModel:(YQUserModel *)user{
    [_db open];
    
    BOOL result = [_db executeUpdate:@"insert into 't_user'(account,password) values(?,?)" withArgumentsInArray:@[user.account,user.password]];
    
    if (result) {

    } else {

    }
    [_db close];
}
复制代码

删除数据

- (void)deleteUserModel:(NSString *)account{
    [_db open];
    
    BOOL result = [_db executeUpdate:@"delete from 't_user' where account = ?" withArgumentsInArray:@[account]];
    
    if (result) {

    } else {

    }
    [_db close];
}
复制代码

更新数据

- (void)updateUserModel:(YQUserModel *)user{
    [_db open];
    BOOL result = [_db executeUpdate:@"update 't_user' set password = ? where account = ?" withArgumentsInArray:@[user.password,user.account]];
    
    if (result) {

    } else {
    
    }
    [_db close];
}
复制代码

查询一条数据或所有数据

- (NSString *)searchPasswordWithAccount:(NSString *)account{
    [_db open];
    FMResultSet *result = [_db executeQuery:@"select * from 't_user' where account = ?" withArgumentsInArray:@[account]];
    
    NSString *password = [[NSString alloc] init];
    while ([result next]) {
       password = [result stringForColumn:@"password"];
    }
    
    [_db close];
    return password;
}

- (NSMutableArray *)getAllAccounts{
    [_db open];
    NSMutableArray *accountArr = [NSMutableArray array];
    FMResultSet *result = [_db executeQuery:@"select * from 't_user'"];
    while ([result next]) {
        NSString *account = [result stringForColumn:@"account"];
        [accountArr addObject:account];
    }
    [_db close];
    
    return accountArr;
}
复制代码
关注下面的标签,发现更多相似文章
评论