FMDB的用法讲解

来源:互联网 发布:淘宝小号哪里买的安全 编辑:程序博客网 时间:2024/05/08 12:30

今天写一下 关于FMDB的笔记,FMDB是一个强大的第三方库,对sql语句进行了封装,并在并发数据库操作上做了处理,听起来那么像hibernate 似的,本文主要翻译于github上对FMDB的使用,地址:https://github.com/ccgus/fmdb,另外推荐大家一个sql语法的教学网址:http://www.runoob.com/sqlite/sqlite-constraints.html,希望可以帮助大家。

ARC 和 MRC
项目中使用 ARC 还是 MRC,对使用 FMDB 都没有任何影响,FMDB 会在编译项目时自动匹配。

导入
导入FMDB前 先在工程内导入libsqlite3.0.tbd这个库

使用

在 FMDB 中有三个重要的类:
FMDatabase:是一个提供 SQLite 数据库的类,用于执行 SQL 语句。
FMResultSet:用在 FMDatabase 中执行查询的结果的类。
FMDatabaseQueue:在多线程下查询和更新数据库用到的类。

数据库创建
FMDatabase 是通过一个 SQLite 数据库文件路径创建的,此路径可以是以下三者之一:
1,一个文件的系统路径。磁盘中可以不存在此文件,因为如果不存在会自动为你创建。
2,一个空的字符串 @”“。会在临时位置创建一个空的数据库,当 FMDatabase 连接关闭时,该数据库会被删除。
3,NULL。会在内存中创建一个数据库,当 FMDatabase 连接关闭时,该数据库会被销毁。

// 创建数据库示例FMDatabase *db = [FMDatabase databaseWithPath:@"你所要写的地址.db"];

数据库必须是打开状态,才能与之交互。如果没有足够的资源和权限来打开\创建数据库,数据库会打开失败。

数据库更新
SQL 语句中除过 SELECT 语句都可以称之为更新操作。包括 CREATE,UPDATE,INSERT,ALTER,COMMIT,BEGIN,DETACH,DROP,END,EXPLAIN,VACUUM,REPLACE 等。一般只要不是以 SELECT 开头的 SQL 语句,都是更新语句。

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

数据库查询
通过调用 -executeQuery… 方法之一执行 SELECT 语句进行数据库查询操作。

执行查询操作后,如果成功会返回一个 FMResultSet 对象,反之会返回 nil。通过 -lastErrorMessage 和 -lastErrorCode 方法可以确定为什么会查询失败。

为了遍历查询结果,需要 while() 循环,然后逐条记录查看。在 FMDB 中,可以通过下面的简单方式实现:

FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];while ([s next]) {    // 每条记录的检索值,即数据库查询出来的某条数据;}

即使只需要获取一个数据,也还是必须在访问查询结果前调用 -[FMResultSet next]。

// 示例FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];if ([s next]) {    int totalCount = [s intForColumnIndex:0];    //此处可以通过index取值,也可以通过 键 来取值}

FMResultSet 提供了很多方便的方法来查询数据:

intForColumn:
longForColumn:
longLongIntForColumn:
boolForColumn:
doubleForColumn:
stringForColumn:
dateForColumn:
dataForColumn:
dataNoCopyForColumn:
UTF8StringForColumn:
objectForColumn:

这些方法都有一个 {type}ForColumnIndex: 变体,是基于列的位置来查询数据。

通常情况下,一个 FMResultSet 没有必要手动 -close,因为结果集合 (result set) 被释放或者源数据库关闭会自动关闭。

关闭数据库
当对数据库进行查询和更新操作完成后,需要调用 -close 关闭数据库 FMDatabase 的连接。

// 示例[db close];

事务
FMDatabase 可以通过调用方法来开始和提交事务,也可以通过执行开始\结束事务 (begin\end transaction) 语句。

多语句和批处理
FMDatabase 可以通过 -executeStatements:withResultBlock: 方法在一个字符串中执行多语句。

// 示例NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"                 "create table bulktest2 (id integer primary key autoincrement, y text);"                 "create table bulktest3 (id integer primary key autoincrement, z text);"                 "insert into bulktest1 (x) values ('XXX');"                 "insert into bulktest2 (y) values ('YYY');"                 "insert into bulktest3 (z) values ('ZZZ');";success = [db executeStatements:sql];sql = @"select count(*) as count from bulktest1;"       "select count(*) as count from bulktest2;"       "select count(*) as count from bulktest3;";success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {    NSInteger count = [dictionary[@"count"] integerValue];    XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);    return 0;}];

数据处理
当给 FMDB 提供 SQL 语句时,在插入前不应该处理任何数据,而应该使用标准的 SQLite 的绑定语法。

// 示例INSERT INTO myTable VALUES (?, ?, ?)

? 问号在 SQLite 中意为即将插入的值的占位符,FMDB 执行语句的方法都接受多个参数 (或者参数集合,比如 NSArray,NSDictionary,va_list),它们都会正确转义。

// 示例INSERT INTO myTable VALUES (?, ?, ?)

也可以使用命名参数语法:

// 示例 这些语法问题可以在我推荐的链接里学习INSERT INTO myTable VALUES (:id, :name, :value)

这些参数必须以冒号开头,SQLite 自身支持其他字符,但是命名时字典的键内部以冒号开头,就不能在你的字典的键中包含冒号。

// 示例NSDictionary *argsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"My Name", @"name", nil];[db executeUpdate:@"INSERT INTO myTable (name) VALUES (:name)" withParameterDictionary:argsDict];

因此,不应该写类似下面这行一样的错误代码:

// 错误示例[db executeUpdate:[NSString stringWithFormat:@"INSERT INTO myTable VALUES (%@)", @"this has \" lots of ' bizarre \" quotes '"]];

而应该这样写:

// 正确示例[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has \" lots of ' bizarre \" quotes '"];

也可以使用 -execute*WithFormat: 这个方法将数字转换成字符串:

// 转换成字符串示例[db executeUpdateWithFormat:@"INSERT INTO myTable VALUES (@d)", 42];

-execute*WithFormat: 这些方法后面都可以接格式字符串参数,以下 % 百分号格式符都是可以识别的:%@, %c, %s, %d, %D, %i, %u, %U, %hi, %hu, %qi, %qu, %f, %g, %ld, %lu, %lld, %llu。使用其他格式符可能会出现不可预知的问题。出于某种原因,可能需要在你的 SQL 语句中使用 % 字符,应该使用百分号转义一下 %%。

FMDatabaseQueue 队列和线程安全
在多线程中同时使用 FMDatabase 单例是极其错误的想法,会导致每个线程创建一个 FMDatabase 对象。不要跨线程使用单例,也不要同时跨多线程,不然会奔溃或者异常。

因此不要实例化一个 FMDatabase 单例来跨线程使用。

相反,使用 FMDatabaseQueue,下面就是它的使用方法:

第一,创建队列。

// 创建 FMdatabaseQueue 示例FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];

然后这样使用:

// 示例[queue inDatabase:^(FMDatabase *db) {    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];    FMResultSet *rs = [db executeQuery:@"select * from foo"];    while ([rs next]) {        ...    }}];

把操作放在事务中也很简单明了,比如:

// 示例[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];    if (whoopsSomethingWrongHappened) {        *rollback = YES;        return;    }    // ...    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];}];

FMDatabase 将块代码 block 运行在一个串行队列上,即使在多线程同时调用 FMDatabaseQueue 的方法,它们仍然还是顺序执行。这种查询和更新方式不会影响其它,是线程安全的。

关于oc的FMDB的翻译就这么多 或许大家看了这么多还不知道如何系统使用一次,我贴一段代码给大家:

//创建数据库+(void)creatTablefh{    FMDatabase * db=[EGDatabaseUtil getDB];//创建表所在的文件地址    if (![db open])    {        [db close];        NSLog(@"打开数据库失败");        return;    }    [db setShouldCacheStatements:YES];    if (![db tableExists:@"FetalHeartRateTable"])    {        [db executeUpdate:@"create table if not exists FetalHeartRateTable(uid integer, record_time integer ,average integer, duration integer,value Varchar, screenshot Varchar,media Varchar,fid integer, isAdult integer,isUploadSuccess integer,snapShotData Varchar ,primary key(record_time,uid))"];    }    [db close];}//表字段的格式 大家可以通过我推荐的链接 查看。
表的地址+(NSString *)getDBFilePath{    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/db.sqlite"];}//创建数据库+ (FMDatabase * )getDB{    //NSLog(@"%@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/db.sqlite"]);    if (!_db) {        _db = [[FMDatabase alloc]initWithPath:[self getDBFilePath]];    }    return _db;}
我们以查询语句为例 :+(NSMutableArray *)getAllFetalHeartDataById :(int)userId{    FMDatabase * db=[EGDatabaseUtil getDB];    if (![db open])    {        [db close];        return nil;    }    FMResultSet *set=[db executeQuery:@"select * from FetalHeartRateTable  where uid = ? ORDER BY record_time",[NSNumber numberWithInt:userId]];    NSMutableArray * array=[[NSMutableArray alloc]initWithCapacity:0];    while ([set next])//查找表的下一列的所有数据    {        EGFeltaHeartRateModel * fh=[[EGFeltaHeartRateModel alloc]init];        fh.uid = [set intForColumn:@"uid"];        fh.record_time = [set doubleForColumn:@"record_time"];        fh.average = [set doubleForColumn:@"average"];        fh.duration = [set intForColumn:@"duration"];        fh.values = [set stringForColumn:@"value"];        fh.screenshot = [set stringForColumn:@"screenshot"];        fh.media = [set stringForColumn:@"media"];        fh.fid = [set intForColumn:@"fid"];        fh.isAdult = [set intForColumn:@"isAdult"];        [array addObject:fh];    }    [set close];    [db close];    return array;}

这样我们就可以完成整个 数据库的操作流程。 谢谢

1 0