博客> FMDB使用心得之二(线程安全)
FMDB使用心得之二(线程安全)
2017-12-12 15:55 评论:0 阅读:1016 tianya2416
runtime 运行时 FMDB 数据库

前面一篇我们提到使用FMDB操作数据库的时候要注意线程安全问题,其实FMDB早就为我们考虑好这些事情了.我们只需要使用FMDB提供的FMDatabaseQueue这个对象来操作我们的数据库就可以了。

1、创建数据库创建表

    - (void)createDateBaseQueueTable
{
    NSString * stringPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/House"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath]) {
        BOOL res = [[NSFileManager defaultManager]createDirectoryAtPath:stringPath withIntermediateDirectories:YES attributes:nil error:nil];
        if (res) {
            NSLog(@"create successful");
        }
    }
    NSString * dbPatch = [stringPath stringByAppendingPathComponent:@"weisheng.sqlite"];
    if (!_dataBaseQueue) {
        _dataBaseQueue = [FMDatabaseQueue databaseQueueWithPath:dbPatch];
    }

    [_dataBaseQueue inDatabase:^(FMDatabase * dataBase) {
        if ([dataBase open]) {
            //数据库建表
            NSString * sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS ContactsChangeFriend (data text,user_id text PRIMARY KEY)"];
            [dataBase executeUpdate:sql];
            [dataBase close];
        }
        else
        {

        }
    }];
}

2、插入一条数据

- (void)insertTheDataToGroupDataBase:(weishengModel *)modelObject
{
    [self createDateBaseQueueTable];
    [_dataBaseQueue inDatabase:^(FMDatabase * db) {
        if ([db open]) {
            NSData * data = [self archivedDataForOfflineResourceData:modelObject];
            NSString * v5TableSql = [NSString stringWithFormat:@"insert or replace into ContactsChangeFriend (data,user_id) values (?,?)"];
            BOOL res = [db executeUpdate:v5TableSql withArgumentsInArray:@[data,modelObject.user_id]];
            if (res) {

            }
            [db close];
        }
    }];
}

3、使用事务来批量插入数据

- (void)insertTheDataToGroupWithDataBase:(NSArray *)arrayModelObject
{
    [self createDateBaseQueueTable];
    [_dataBaseQueue inDatabase:^(FMDatabase * db) {
        if ([db open]) {
             [db beginTransaction];
            for (weishengModel * modelObject in arrayModelObject) {
                NSData * data = [self archivedDataForOfflineResourceData:modelObject];
                NSString * v5TableSql = [NSString stringWithFormat:@"insert or replace into ContactsChangeFriend (data,user_id) values (?,?)"];
                BOOL res = [db executeUpdate:v5TableSql withArgumentsInArray:@[data,modelObject.user_id]];
                if (res) {

                }
            }
            [db commit];
            [db close];
        }
    }];
}

4、更新数据

- (void)updateTheDataToGroupDataBase:(weishengModel *)modelObject
{
    [self createDateBaseQueueTable];
    [_dataBaseQueue inDatabase:^(FMDatabase * db) {
        if ([db open]) {
            NSData * data = [self archivedDataForOfflineResourceData:modelObject];
            NSString * v5TableSql = [NSString stringWithFormat:@"update ContactsChangeFriend set data = ? where user_id = ?"];
            BOOL res = [db executeUpdate:v5TableSql withArgumentsInArray:@[data,modelObject.user_id]];
            if (res) {

            }
            [db close];
        }
    }];
}

5、删除数据

- (void)deleteTheDataToGroupDataBase:(weishengModel *)modelObject
{
[self createDateBaseQueueTable];
  [_dataBaseQueue inDatabase:^(FMDatabase *db) {
      if ([db open]) {
          [db beginTransaction];
          NSString * v5TableSql = [NSString stringWithFormat:@"delete from ContactsChangeFriend where user_id = %@",modelObject.user_id];
          BOOL res = [db executeUpdate:v5TableSql];
          if (res) {
              [db commit];
              NSLog(@"success to delete db table data");
          }else
          {
              NSLog(@"error when delete db table data");
          }
          [db close];
      }
  }];

}

6、读取数据

- (void)readTheDataToGroupDataBase:(void(^)(NSArray * arrayData))readTheDataToDataBaseBlock
{
    [self createDateBaseQueueTable];
    [_dataBaseQueue inDatabase:^(FMDatabase *db) {
        if ([db open]) {
            NSString * sql = [NSString stringWithFormat:
                              @"select * from ContactsChangeFriend order by user_id"];
            FMResultSet * rs = [db executeQuery:sql];
            NSData * data;
            NSMutableArray * array = [[NSMutableArray alloc]init];
            while ([rs next])
            {
                data = [rs dataForColumn:@"data"];
                weishengModel * model = [self unarchiveForData:data];
                [array addObject:model];
            }
            [db close];
            readTheDataToDataBaseBlock(array);
        }
    }];

}

7、删除表

- (void)DropTheTableGroupDataBase
{
    [self createDateBaseQueueTable];
    [_dataBaseQueue inDatabase:^(FMDatabase *db) {
        if ([db open]) {
            NSString * sqlstr = [NSString stringWithFormat:@"drop table ContactsChangeFriend"];
            BOOL res =  [db executeUpdate:sqlstr];
            if (res) {
                NSLog(@"drop table successful");
            }else
            {
                NSLog(@"drop table fail");
            }
            [db close];
        }
    }];

}

以上就是我使用FMDB的一些心得,欢迎各位学者一起来学习与成长附上demo Enter your link description here:

收藏
2
sina weixin mail 回到顶部