初识 FMDB
iOS中原生的SQLite API在进行数据存储的时候,需要使用C语言中的函数,操作比较麻烦。于是,就出现了一系列将SQLite API进行封装的库,例如FMDB、PlausibleDatabase、sqlitepersistentobjects等。
FMDB是一款简洁、易用的封装库。因此,在这里推荐使用第三方框架FMDB,它是对libsqlite3框架的封装,用起来的步骤与SQLite使用类似,并且它对于多线程的并发操作进行了处理,所以是线程安全的。
FMDB pk Sqlite
- 优点
- 对多线程的并发操作进行处理,所以是线程安全的;
- 以OC的方式封装了SQLite的C语言API,使用起来更加的方便;
- FMDB是轻量级的框架,使用灵活。
- 缺点
- 因为它是OC的语言封装的,只能在ios开发的时候使用,所以在实现跨平台操作的时候存在局限性。
FMDB框架中重要的框架类
- FMDatabase
- FMDatabase对象就代表一个单独的SQLite数据库,用来执行SQL语句
- FMResultSet
- 使用FMDatabase执行查询后的结果集
- FMDatabaseQueue
- 用于在多线程中执行多个查询或更新,它是线程安全的
FMDB使用步骤
载FMDB文件GitHub,并将FMDB文件夹添加到项目中(也可使用CocoaPods导入)
导入libsqlite3.0框架,导入头文件FMDatabase.h
-
代码实现,与SQLite使用步骤相似,创建数据库路径,获得数据库路径,打开数据库,然后对数据库进行增、删、改、查操作,最后关闭数据库。
数据库创建
创建FMDatabase对象时参数为SQLite数据库文件路径,该路径可以是以下三种方式之一
- 文件路径。该文件路径无需真实存在,如果不存在会自动创建
- 空字符串(@“”)。表示会在临时目录创建一个空的数据库,当FMDatabase连接关闭时,文件也会被删除
- NULL。将创建一个内在数据库,同样的,当FMDatabase连接关闭时,数据将会被销毁
数据库使用FMDB框架代码操作
- 使用FMDataBase类建立数据库
- (void)createDataBase {
// 1.获得数据库文件的路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName = [doc stringByAppendingPathComponent:@"student.sqlite"];
// 2.获得数据库
FMDatabase *db = [FMDatabase databaseWithPath:fileName];
self.db = db;
// 3.使用如下语句,如果打开失败,可能是权限不足或者资源不足,通常打开完操作操作后,需要调用 close 方法来关闭数据库。
// 在和数据库交互 之前,数据库必须是打开的。如果资源或权限不足无法打开或创建数据库,都会导致打开失败。
if ([db open]) {
// 4.创建表
bool result = [db executeUpdate:@"create table if not exists t_student(id integer PRIMARY KEY AUTOINCREMENT, name text not null, age integer not null)"];
if (result) {
NSLog(@"创建表格成功");
}
}
}
- 查看 sql 表
- 根据路径fileName在Finder中搜索.sqlite文件,并复制到桌面
-
在 App Store 下载 Datum free 免费软件,然后打开.sqlite 文件即可.
使用FMDataBase类执行数据库命令SQL
一切不是SELECT命令的命令都视为更新。这包括 CREAT,UPDATE,INSERT,ALTER,BEGIN,COMMIT,DETACH,DELETE,DROP,END,EXPLAIN,VACUUM,REPLACE等。
简单来说,只要不是以SELECT开头的命令都是更新命令。
执行更新返回一个BOOL值。YES表示 执行成功,否则表示有错误。你可以调用 -lastErrorMessage 和 -lastErrorCode方法来得到更多信息。
- 使用FMDataBase类执行数据库插入命令SQLinsert into
- (void)insertData {
int age = 29;
NSString *name = @"张小飞";
//1.executeUpdate:不确定的参数用?来占位(后面参数必须是 OC 对象,;代表语句结束)
[self.db executeUpdate:@"insert into t_student (name,age) values (?,?);",name,@(age)];
//2.executeUpdateWithForamat:不确定的参数用%@,%d等来占位(参数为原始数据类型,执行语句不区分大小写)
[self.db executeUpdateWithFormat:@"insert into t_student (name,age) values (%@,%i);",name,age];
//3.参数是数组的使用方式
[self.db executeUpdate:@"insert into t_student(name,age) values (?,?);" withArgumentsInArray:@[name,@(age)]];
}
- 使用FMDataBase类执行数据库删除命令SQLdelete
- (void)deleteData {
int idNum = 1;
//1.不确定的参数用?来占位(后面参数必须是 OC 对象,需要将 int 包装成 OC 对象)
[self.db executeUpdate:@"delete from t_student where id = ?;",@(idNum)];
//2.不确定的参数用%@,%d 等来占位
[self.db executeUpdateWithFormat:@"delete from t_student where name = %@;",@"chen"];
}
- 使用FMDataBase类执行数据库修改命令SQLupdate
- (void)updateData {
NSString *oldName = @"chenliang";
NSString *newName = @" 张小飞";
[self.db executeUpdate:@"update t_student set name = ? where name = ?",newName,oldName];
}
- 使用FMDataBase类执行数据库查询命令SQL select ... from
- SELECT命令就是查询,执行查询的方法是以-excuteQuery开头的。
- 执行查询时,如果成功返回FMResultSet对象,错误返回nil。与执行更新相当,支持使用NSError参数。
- 同时,你也可以使用-lastErrorCode和-lastErrorMessage获知错误信息。
- FMResultSet获取不同数据格式的方法
- intForColumn:
- longForColumn:
- longLongIntForColumn:
- boolForColumn:
- doubleForColumn:
- stringForColumn:
- dataForColumn:
- dataNoCopyForColumn:
- UTF8StringForColumnIndex
- objectForColumn:
- 使用FMResultSet获取查询语句结果
- (void)sqlData {
// 查询整个表
FMResultSet *resultSet = [self.db executeQuery:@"select * from t_student"];
// 根据条件查询
FMResultSet *resultSet = [self.db executeQuery:@"select * from t_student where id
- 使用FMDataBase类执行数据库销毁命令SQL drop ...
- (void)dropDataBase {
// 如果存在,则销毁
[self.db executeUpdate:@"drop table if exists t_student;"];
}
使用FMDatabaseQueue类实现多线程操作
在多个线程中同时使用一个FMDatabase实例是不明智的。现在你可以为每 个线程创建一个FMDatabase对象,不要让多个线程分享同一个实例,他无 法在多个线程中同事使用。否则程序会时不时崩溃或者报告异常。所以,不要 初始化FMDatabase对象,然后在多个线程中使用。这时候,我们就需要使 用FMDatabaseQueue来创建队列执行事务。
- (void)createDatabaseQueue {
int age1 = arc4random_uniform(100);
int age2 = arc4random_uniform(100);
int age3 = arc4random_uniform(100);
NSString *name1 = [NSString stringWithFormat:@"chen - %d",age1];
NSString *name2 = [NSString stringWithFormat:@"chen - %d",age2];
NSString *name3 = [NSString stringWithFormat:@"chen - %d",age3];
// 1.获得数据库文件的路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName = [doc stringByAppendingPathComponent:@"student.sqlite"];
//1.创建队列
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:fileName];
__block bool whoopsSomethingWrongHappened = true;
//2.把任务包装到事务里
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
whoopsSomethingWrongHappened = [db executeUpdate:@"insert into t_student(name,age) values (?,?);" withArgumentsInArray:@[name1,@(age1)]];
whoopsSomethingWrongHappened = [db executeUpdate:@"insert into t_student(name,age) values (?,?);" withArgumentsInArray:@[name2,@(age2)]];
whoopsSomethingWrongHappened = [db executeUpdate:@"insert into t_student(name,age) values (?,?);" withArgumentsInArray:@[name3,@(age3)]];
// 如果有错误,则返回
if (!whoopsSomethingWrongHappened) {
*rollback = YES;
return;
}
}];
}
项目连接地址
本文参考 陈向阳哈数据库第三方框架FMDB详细讲解,非常感谢该作者.