iOS中FMDB数据库之增删改查使用实例

2020-01-20 12:47:44王旭

建表:


// 建表
- (void)createTable {
  NSLog(@"%s", __func__);

  NSFileManager *fileManager = [NSFileManager defaultManager];
  if ([fileManager fileExistsAtPath:self.dbPath] == NO) {
    // create it
    FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
    if ([db open]) {
      NSString *sql = @"CREATE TABLE 'User' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , 'name' VARCHAR(30), 'password' VARCHAR(30))";
      BOOL res = [db executeUpdate:sql];
      if (!res) {
        NSLog(@"error when creating db table");
      } else {
        NSLog(@"success to creating db table");
      }
      [db close];
    } else {
      NSLog(@"error when open db");
    }
  }
}

插入数据:


// 插入数据
- (void)insertData {
  NSLog(@"%s", __func__);

  static int idx = 1;
  FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
  if ([db open]) {

    NSString *sql = @"insert into user (name, password) values(?, ?) ";
    NSString *name = [NSString stringWithFormat:@"ZL%d", idx++];

    BOOL res = [db executeUpdate:sql, name, @"girl"];
    if (!res) {
      NSLog(@"error to insert data");
    } else {
      NSLog(@"success to insert data");

      ZLTestModel *model = [ZLTestModel modelWith:name id:idx];
      [self.userArr addObject:model];
      [self.tableView reloadData];
    }
    [db close];
  }
}

更新数据:


// 更新数据
- (void)updateData {
  NSLog(@"%s", __func__);

  FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
  if ([db open]) {
    NSString *sql = @"UPDATE USER SET id = ? WHERE name = ?";
    BOOL res = [db executeUpdate:sql, @"1", @"zl"];
    if (!res) {
      NSLog(@"error to UPDATE data");
    } else {
      NSLog(@"success to UPDATE data");
      [self queryData];
    }
    [db close];
  }
}

删除数据:


// 删除数据
- (void)deleteData {
  NSLog(@"%s", __func__);
  FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
  if ([db open]) {
    NSString *sql = @"delete from user";
    BOOL res = [db executeUpdate:sql];
    if (!res) {
      NSLog(@"error to delete db data");
    } else {
      NSLog(@"success to delete db data");

      [self.userArr removeAllObjects];
      [self.tableView reloadData];
    }
    [db close];
  }
}

查询数据:


// 查询数据
- (void)queryData {
  NSLog(@"%s", __func__);

  FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
  if ([db open]) {
    NSString *sql = @"select *from user";
    FMResultSet *rs = [db executeQuery:sql];
    while ([rs next]) {
      int userId = [rs intForColumn:@"id"];
      NSString *name = [rs stringForColumn:@"name"];
      NSString *pass = [rs stringForColumn:@"password"];
      NSLog(@"user id = %d, name = %@, pass = %@", userId, name, pass);
      ZLTestModel *model = [ZLTestModel modelWith:name id:userId];
      [self.userArr addObject:model];
      [self.tableView reloadData];
    }
    [db close];
  }
}