程序员大数据 爬虫Python AI Sql

SQLite数据库框架--FMDB

2015-11-27  本文已影响472人  Jimmy_P

FMDB概述


什么是FMDB

FMDB的优点

FMDB的github地址

FMDB基本使用


FMDB有三个核心类

FMDatabase

** FMResultSet**

** FMDatabaseQueue**

FMDB打开数据库

通过指定SQLite数据库文件路径来创建FMDatabase对象

FMDatabase *db = [FMDatabase databaseWithPath:path];
if (![db open]) 
{
    NSLog(@"数据库打开失败!");
}

文件路径(path)有三种情况:

执行更新

在FMDB中,除查询以外的所有操作,都称为“更新”create、drop、insert、update、delete等

  - (BOOL)executeUpdate:(NSString*)sql, ...
  - (BOOL)executeUpdateWithFormat:(NSString*)format, ...
  - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments
  [db executeUpdate:@"UPDATE t_student SET age = ? WHERE name = ?;", @20, @"Jack"]

执行查询

查询方法

- (FMResultSet *)executeQuery:(NSString*)sql, ...
- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ...
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments
  // 查询数据
  FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_student"];

  // 遍历结果集
  while ([rs next]) {
      NSString *name = [rs stringForColumn:@"name"];
      int age = [rs intForColumn:@"age"];
      double score = [rs doubleForColumn:@"score"];
  }

FMDatabaseQueue


  FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
  [queue inDatabase:^(FMDatabase *db) {
     [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Jack"];
     [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Rose"];
     [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Jim"];

     FMResultSet *rs = [db executeQuery:@"select * from t_student"];
     while ([rs next]) {
     // …
     }
  }];
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
  [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Jack"];
  [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Rose"];
  [db executeUpdate:@"INSERT INTO t_student(name) VALUES (?)", @"Jim"];

  FMResultSet *rs = [db executeQuery:@"select * from t_student"];
  while ([rs next]) {
      // …
  }
}];
 rollback = YES;

上一篇下一篇

猜你喜欢

热点阅读