• FMDB的简单使用


    1、什么是FMDB?

    • FMDB是iOS平台的SQLite数据库框架
    • FMDB以OC的方式封装了SQLite的C语言API。
    • 无论项目中使用 ARC 还是 MRC,对 FMDB 都没有任何影响,FMDB 会在编译项目时自动匹配。

    2、FMDB主要的类。

    2.1、FMDatabase
    一个FMDatabase对象就代表一个单独的SQLite数据库,用来执行SQL语句。通过指定SQLite数据库文件路径来创建FMDatabase对象。
    在FMDB中,一般只要不是以 SELECT 开头的 SQL 语句,都是更新语句,包括CREATE,UPDATE,INSERT,ALTER,COMMIT,BEGIN,DETACH,DROP,END,EXPLAIN,VACUUM,REPLACE等。使用executeUpdate:方法执行更新:
    • - (BOOL)executeUpdate:(NSString*)sql, ...;
    • - (BOOL)executeUpdateWithFormat:(NSString*)format, ...;
    • - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;

    执行更新语句后会返回一个 BOOL 值,返回YES表示执行更新语句成功,返回NO表示出现错误,可以通过调用 -lastErrorMessage 和 -lastErrorCode 方法获取更多错误信息。

    创库创表:

    •  1 // 获取数据库文件路径
       2 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"test.sqlite"];
       3 // 创建数据库
       4 FMDatabase *db = [FMDatabase databaseWithPath:path];
       5 self.db = db;
       6 if (db.open) {// 打开数据库,数据库必须是打开状态,才能与之交互。如果没有足够的资源和权限来打开或者创建数据库,数据库会打开失败。
       7     NSLog(@"打开成功");
       8     // 创表
       9     BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_person (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL)"];
      10     if (result) {
      11         NSLog(@"创表成功");
      12     } else {
      13         NSLog(@"创表失败:%@", [self.db lastErrorMessage]);
      14     }
      15 } else {
      16     NSLog(@"打开失败");
      17 }

    添加数据:

    • 1 // executeUpdate:不确定的参数用?来占位,所有参数都必须是对象。
      2 //    BOOL result = [self.db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?)", @"jick", @(arc4random_uniform(20))];
      3 // executeUpdateWithFormat:不确定的参数用%@、%f、%d、%u等来占位。
      4 BOOL result = [self.db executeUpdateWithFormat:@"INSERT INTO t_person (name, age) VALUES (%@, %d)", @"jick", arc4random_uniform(20)];
      5 if (result) {
      6     NSLog(@"添加成功");
      7 } else {
      8     NSLog(@"添加失败:%@", [self.db lastErrorMessage]);
      9 }

    删除、更新数据:同创表、添加数据方法相同,只需修改SQL语句就行了。

    • 关闭数据库:  [self.db close];

    文件路径有三种情况:

    • 具体文件路径:如果不存在会自动创建。
    • 空字符串@"":会在临时目录创建一个空的数据库,当FMDatabase连接关闭时,数据库文件也被销毁。
    • nil:会在内存中创建一个临时数据库,当FMDatabase连接关闭时,数据库会被销毁。

    2.2、FMResultSet。

    使用FMDatabase执行查询后的结果集:
    • - (FMResultSet *)executeQuery:(NSString*)sql, ...;
    • - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ...;
    • - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;
    执行查询操作后,如果成功会返回一个FMResultSet对象,反之会返回nil。通过 -lastErrorMessage 和 -lastErrorCode 方法可以确定查询失败原因。
    为了遍历查询结果,需要while()循环,然后逐条记录查看。在 FMDB 中,可以通过下面的简单方式实现:
    • 1 // 执行查询语句
      2 FMResultSet *result = [self.db executeQuery:@"SELECT * FROM t_person WHERE age < 15"];
      3 // 遍历结果,它是基于列的位置来查询数据。
      4 while (result.next) {
      5     int ID = [result intForColumn:@"id"];
      6     NSString *name = [result stringForColumn:@"name"];
      7     int age = [result intForColumn:@"age"];
      8     NSLog(@"id = %d, name = %@, age = %d", ID, name, age);
      9 }
    • 关闭数据库:  [self.db close]; 
    2.3、FMDatabaseQueue。
    FMDatabase这个类是线程不安全的,如果在多个线程中同时使用一个FMDatabase实例,会造成数据混乱等问题。为了保证线程安全,FMDB提供了FMDatabaseQueue类。
    • FMDatabaseQueue的创建:
    •  1 数据库文件路径
       2 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"test.sqlite"];
       3 // 创建数据库
       4 FMDatabaseQueue *dbq = [FMDatabaseQueue databaseQueueWithPath:path];
       5 self.dbq = dbq;
       6 // 打开数据库
       7 [dbq inDatabase:^(FMDatabase *db) {
       8     BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_person (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL)"]; // 创表
       9     if (result) {
      10         NSLog(@"创表成功");
      11     } else {
      12         NSLog(@"创表失败:%@", [db lastErrorMessage]);
      13     }
      14 }];
    • 添加数据:更新、删除和添加数据的方法类似。
      1 [self.dbq inDatabase:^(FMDatabase *db) {
      2     BOOL result = [db executeUpdateWithFormat:@"INSERT INTO t_person (name, age) VALUES (%@, %d)", @"jick", arc4random_uniform(20)];
      3     if (result) {
      4         NSLog(@"添加成功");
      5     } else {
      6         NSLog(@"添加失败");
      7     }
      8 }];
    • 查询数据:
       1 [self.dbq inDatabase:^(FMDatabase *db) {
       2     // 执行查询语句
       3     FMResultSet *result = [db executeQuery:@"SELECT * FROM t_person WHERE age < 15"];
       4     // 遍历结果
       5     while (result.next) {
       6         int ID = [result intForColumn:@"id"];
       7         NSString *name = [result stringForColumn:@"name"];
       8         int age = [result intForColumn:@"age"];
       9         NSLog(@"id = %d, name = %@, age = %d", ID, name, age);
      10     }
      11 }];
    • 关闭数据库: [self.dbq close]; 

    3、FMDB的多语句、多事务处理

    3.1、多语句的批处理。

    通过-executeStatements:withResultBlock:方法在一个字符串中执行多语句:

    • 创建多张表并添加数据:
    •  1 NSString *sql = [NSString stringWithFormat:
       2                  @"CREATE TABLE IF NOT EXISTS t_person1 (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"
       3                  "CREATE TABLE IF NOT EXISTS t_person2 (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"
       4                  "CREATE TABLE IF NOT EXISTS t_person3 (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"
       5                  "INSERT INTO t_person1 (name, age) VALUES (%@, %d);"
       6                  "INSERT INTO t_person1 (name, age) VALUES (%@, %d);"
       7                  "INSERT INTO t_person2 (name, age) VALUES (%@, %d);"
       8                  "INSERT INTO t_person2 (name, age) VALUES (%@, %d);"
       9                  "INSERT INTO t_person3 (name, age) VALUES (%@, %d);"
      10                  "INSERT INTO t_person3 (name, age) VALUES (%@, %d);",
      11                  @"'jick'", 10, @"'tom'", 15, @"'rose'", 12, @"'jim'", 18, @"'hank'", 11, @"'jone'", 16];
      12 BOOL result = [self.db executeStatements:sql];
      13 if (result) {
      14     NSLog(@"创表并添加数据成功");
      15 } else {
      16     NSLog(@"创表或添加数据失败:%@", [self.db lastErrorMessage]);
      17 }
    • 查询多张表的多个字段值:
       1 NSString *sql = @"SELECT * FROM t_person1 WHERE age < 30;"
       2                 "SELECT * FROM t_person2 WHERE age < 30;"
       3                 "SELECT * FROM t_person3 WHERE age < 30;";
       4 [self.db executeStatements:sql withResultBlock:^int(NSDictionary *resultsDictionary) {
       5     int ID = [resultsDictionary[@"id"] intValue];
       6     NSString *name = resultsDictionary[@"name"];
       7     int age = [resultsDictionary[@"age"] intValue];
       8     NSLog(@"name = %@, id = %d, age = %d", name, ID, age);
       9     return 0;
      10 }];

    3.2、FMDataba事务处理。

    在FMDatabase/FMDatabaseQueue中通过begin/commit语句来开始和提交事务。

    • 1 //    [self.db executeUpdate:@"begin exclusive transaction"]; // 用SQL语句的方式开启事务
      2 [self.db beginTransaction]; // 开启事务
      3 [self.db executeUpdateWithFormat:@"INSERT INTO t_person1 (name, age) VALUES (%@, %d);",@"'jick1'", 23];
      4 [self.db executeUpdateWithFormat:@"INSERT INTO t_person2 (name, age) VALUES (%@, %d);",@"'jick1'", 26];
      5 //    [self.db executeUpdate:@"rollback transaction"]; // 用SQL语句的方式中途回滚
      6 //    [self.db rollback]; // 中途回滚。
      7 [self.db executeUpdateWithFormat:@"INSERT INTO t_person3 (name, age) VALUES (%@, %d);",@"'jick1'", 21];
      8 //    [self.db executeUpdate:@"commit transaction"]; // 用SQL语句的方式提交事务
      9 [self.db commit]; // 提交事务

    在FMDatabaseQueue中通过调用方法来提交事务。

    • 1 [self.dbq inTransaction:^(FMDatabase *db, BOOL *rollback) {
      2     [db executeUpdateWithFormat:@"INSERT INTO t_person1 (name, age) VALUES (%@, %d);",@"'jick1'", 23];
      3     [db executeUpdateWithFormat:@"INSERT INTO t_person2 (name, age) VALUES (%@, %d);",@"'jick1'", 26];
      4     // *rollback = YES; // 中途回滚
      5     [db executeUpdateWithFormat:@"INSERT INTO t_person3 (name, age) VALUES (%@, %d);",@"'jick1'", 21];
      6 }];

    4、在Swift中使用FMDB。

    在Swift项目中使用 FMDB,需要做以下步骤:
    • 将 FMDB 的 .m 和 .h 全部文件拖进你的项目。
    • 如果 Xcode 提示创建桥接文件,需要点击创建。如果没有提示,且项目中也没有桥接文件,需要手动添加。
    • 在桥接文件中,添加这行代码:#import "FMDB.h"
    • 可以从 "src/extra/Swift Extension" 文件夹中拷贝 FMDatabaseVariadic.swift 文件到项目中,就可以使用 executeUpdate 和 executeQuery 多参数了。
    做完上述几步,就可以使用 FMDatabase 写 Swift 代码了。
  • 相关阅读:
    jQuery图片切换插件jquery.cycle.js
    UVA
    FragmentPagerAdapter和FragmentStatePagerAdapter的差别
    更改jdk所用内存空间
    一次性能优化将filter转换
    JSP中文件的上传于下载演示样例
    Diskpart工具应用两则:MBR/GPT分区转换 &amp; 基本/动态磁盘转换
    LDD3之并发和竞态-completion(完毕量)的学习和验证
    二维码的扫描、生成
    输入一行字符,分别统计出包括英文字母、空格、数字和其他字符的个数
  • 原文地址:https://www.cnblogs.com/hankkk/p/5785075.html
Copyright © 2020-2023  润新知