1、简述:
FMDB是iOS平台的SQLite数据库框架,是对libsqlite3框架的封装
FMDB以OC的方式封装了SQLite的C语言API
2、FMDB的优点:
使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码
对比苹果自带的Core Data框架,更加轻量级和灵活
提供了多线程安全的数据库操作方法,有效地防止数据混乱
3、FMDB的github地址 传送门
4、FMDB的三个核心类
FMDatabase —— 一个FMDatabase对象就代表一个单独的SQLite数据库 用来执行SQL语句
FMResultSet —— 使用FMDatabase执行查询后的结果集
FMDatabaseQueue —— 用于在多线程中执行多个查询或更新,它是线程安全的
1.什么是FMDB
iOS中使用C语言函数对原生SQLite数据库进行增删改查操作,复杂麻烦,于是,就出现了一系列将SQLite API封装的库,如FMDB
FMDB是针对libsqlite3框架进行封装的三方,它以OC的方式封装了SQLite的C语言的API,使用步骤与SQLite相似
FMDB的优点是:
(1) 使用时面向对象,避免了复杂的C语言代码
(2) 对比苹果自带的Core Data框架,更加轻量级和灵活
(3) 提供多线程安全处理数据库操作方法,保证多线程安全跟数据准确性
FMDB缺点:
(1) 因为是OC语言开发,只能在iOS平台上使用,所以实现跨平台操作时存在限制性
FMDB 在Git上的下载链接地址:https://github.com/ccgus/fmdb
2.主要类型
FMDatabase:一个FMDatabase对象代表一个单独的SQLite数据库,通过SQLite语句执行数据库的增删改查操作
FMResultSet:使用FMDatabase对象查询数据库后的结果集
FMDatabaseQueue:用于多线程操作数据库,它保证线程安全
3.FMDB使用方式
(1) GItHub中下载FMDB,将文件导入工程中
(2) 导入libsqlite3.0框架,导入头文件FMDatabase.h
(3) 创建数据库路径,创建数据库,操作前开启数据库,构建操作SQLite语句,数据库执行增删改查操作,操作完关闭数据库
4.FMDB基本使用示例:🌰
(0) 创建Person类
@interface PersonVO : NSObject
@property (nonatomic, assign) int ID;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *phone;
@property (nonatomic, assign) int score;
@end
(1) 使用FMDBbase类创建数据库
//1.创建database路径
NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath = [docuPath stringByAppendingPathComponent:@"test.db"];
NSLog(@"!!!dbPath = %@",dbPath);
//2.创建对应路径下数据库
db = [FMDatabase databaseWithPath:dbPath];
//3.在数据库中进行增删改查操作时,需要判断数据库是否open,如果open失败,可能是权限或者资源不足,数据库操作完成通常使用close关闭数据库
[db open];
if (![db open]) {
NSLog(@"db open fail");
return;
}
//4.数据库中创建表(可创建多张)
NSString *sql = @"create table if not exists t_student ('ID' INTEGER PRIMARY KEY AUTOINCREMENT,'name' TEXT NOT NULL, 'phone' TEXT NOT NULL,'score' INTEGER NOT NULL)";
//5.执行更新操作 此处database直接操作,不考虑多线程问题,多线程问题,用FMDatabaseQueue 每次数据库操作之后都会返回bool数值,YES,表示success,NO,表示fail,可以通过 @see lastError @see lastErrorCode @see lastErrorMessage
BOOL result = [db executeUpdate:sql];
if (result) {
NSLog(@"create table success");
}
[db close];
(2) 插入命令sql语句
/**
增删改查中 除了查询(executeQuery),其余操作都用(executeUpdate)
//1.sql语句中跟columnname 绑定的value 用 ?表示,不加‘’,可选参数是对象类型如:NSString,不是基本数据结构类型如:int,方法自动匹配对象类型
- (BOOL)executeUpdate:(NSString*)sql, ...;
//2.sql语句中跟columnname 绑定的value 用%@/%d表示,不加‘’
- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
//3.sql语句中跟columnname 绑定的value 用 ?表示的地方依次用 (NSArray *)arguments 对应的数据替代
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;
//4.同3 ,区别在于多一个error指针,记录更新失败
- (BOOL)executeUpdate:(NSString*)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error;
//5.同3,区别在于用 ? 表示的地方依次用(NSDictionary *)arguments中对应的数据替代
- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments;
- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args;
*/
//0.直接sql语句
// BOOL result = [db executeUpdate:@"insert into 't_student' (ID,name,phone,score) values(110,'x1','11',83)"];
//1.
// BOOL result = [db executeUpdate:@"insert into 't_student'(ID,name,phone,score) values(?,?,?,?)",@111,@"x2",@"12",@23];
//2.
// BOOL result = [db executeUpdateWithFormat:@"insert into 't_student' (ID,name,phone,score) values(%d,%@,%@,%d)",112,@"x3",@"13",43];
//3.
BOOL result = [db executeUpdate:@"insert into 't_student'(ID,name,phone,score) values(?,?,?,?)" withArgumentsInArray:@[@113,@"x3",@"13",@53]];
if (result) {
NSLog(@"insert into 't_studet' success");
[self showAlertWithTitle:@"insert success" message:nil person:nil];
} else {
[self showAlertWithTitle:[db lastError].description message:nil person:nil];
}
[db close];
(3) 删除命令sql语句
[db open];
///0.直接sql语句
// BOOL result = [db executeUpdate:@"delete from 't_student' where ID = 110"];
//1.
// BOOL result = [db executeUpdate:@"delete from 't_student' where ID = ?",@(111)];
//2.
// BOOL result = [db executeUpdateWithFormat:@"delete from 't_student' where ID = %d",112];
//3.
BOOL result = [db executeUpdate:@"delete from 't_student' where ID = ?" withArgumentsInArray:@[@113]];
if (result) {
NSLog(@"delete from 't_student' success");
[self showAlertWithTitle:@"delete success" message:nil person:nil];
} else {
[self showAlertWithTitle:[db lastError].description message:nil person:nil];
}
[db close];
(4) 更新命令sql语句
[db open];
//0.直接sql语句
// BOOL result = [db executeUpdate:@"update 't_student' set ID = 110 where name = 'x1'"];
//1.
// BOOL result = [db executeUpdate:@"update 't_student' set ID = ? where name = ?",@111,@"x2" ];
//2.
// BOOL result = [db executeUpdateWithFormat:@"update 't_student' set ID = %d where name = %@",113,@"x3" ];
//3.
BOOL result = [db executeUpdate:@"update 't_student' set ID = ? where name = ?" withArgumentsInArray:@[@113,@"x3"]];
if (result) {
NSLog(@"update 't_student' success");
[self showAlertWithTitle:@"update success" message:nil person:nil];
} else {
[self showAlertWithTitle:[db lastError].description message:nil person:nil];
}
[db close];
(5) 查询命令sql语句
/**
FMResultSet根据column name获取对应数据的方法
intForColumn:
longForColumn:
longLongIntForColumn:
boolForColumn:
doubleForColumn:
stringForColumn:
dataForColumn:
dataNoCopyForColumn:
UTF8StringForColumnIndex:
objectForColumn:
*/
[db open];
//0.直接sql语句
// FMResultSet *result = [db executeQuery:@"select * from 't_student' where ID = 110"];
//1.
// FMResultSet *result = [db executeQuery:@"select *from 't_student' where ID = ?",@111];
//2.
// FMResultSet *result = [db executeQueryWithFormat:@"select * from 't_student' where ID = %d",112];
//3.
FMResultSet *result = [db executeQuery:@"select * from 't_student' where ID = ?" withArgumentsInArray:@[@113]];
//4
// FMResultSet *result = [db executeQuery:@"select * from 't_sutdent' where ID = ?" withParameterDictionary:@{@"ID":@114}];
NSMutableArray *arr = [NSMutableArray array];
while ([result next]) {
PersonVO *person = [PersonVO new];
person.ID = [result intForColumn:@"ID"];
person.name = [result stringForColumn:@"name"];
person.phone = [result stringForColumn:@"phone"];
person.score = [result intForColumn:@"score"];
[arr addObject:person];
NSLog(@"从数据库查询到的人员 %@",person.name);
[self showAlertWithTitle:@"query success" message:nil person:person];
}
5.FMDB的事务
(1) 事务定义:
事务(Transaction)是并发操作的基本单位,是指单个逻辑工作单位执行的一系列操作序列,这些操作要不都成功,要不就不成功,事务是数据库维护数据一致性的单位,在每个事务结束时,都能保证数据一致性与准确性,通常事务跟程序是两个不同的概念,一个程序中包含多个事务,事务主要解决并发条件下操作数据库,保证数据
(2) 事务特征:
原子性(Atomic):事务中包含的一系列操作被看作一个逻辑单元,这个逻辑单元要不全部成功,要不全部失败
一致性(Consistency):事务中包含的一系列操作,只有合法的数据被写入数据库,一些列操作失败之后,事务会滚到最初创建事务的状态
隔离性(Isolation):对数据进行修改的多个事务之间是隔离的,每个事务是独立的,不应该以任何方式来影响其他事务
持久性(Durability)事务完成之后,事务处理的结果必须得到固化,它对于系统的影响是永久的,该修改即使出现系统固执也将一直保留,真实的修改了数据库
(3) 事务语句:
/**
transaction:事务 开启一个事务执行多个任务,效率高
1.fmdb 封装transaction 方法,操作简单
- (BOOL)beginTransaction;
- (BOOL)beginDeferredTransaction;
- (BOOL)beginImmediateTransaction;
- (BOOL)beginExclusiveTransaction;
- (BOOL)commit;
- (BOOL)rollback;
等等
*/
开启事务 :beginTransaction
回滚事务:rollback
提交事务:commit
(4) 事务代码
用事务处理一系列数据库操作,省时效率高
- (void)handleTransaction:(UIButton *)sender {
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath = [documentPath stringByAppendingPathComponent:@"test1.db"];
FMDatabase *db = [[FMDatabase alloc]initWithPath:dbPath];
[db open];
if (![db isOpen]) {
return;
}
BOOL result = [db executeUpdate:@"create table if not exists text1 (name text,age,integer,ID integer)"];
if (result) {
NSLog(@"create table success");
}
//1.开启事务
[db beginTransaction];
NSDate *begin = [NSDate date];
BOOL rollBack = NO;
@try {
//2.在事务中执行任务
for (int i = 0; i< 500; i++) {
NSString *name = [NSString stringWithFormat:@"text_%d",i];
NSInteger age = i;
NSInteger ID = i *1000;
BOOL result = [db executeUpdate:@"insert into text1(name,age,ID) values(:name,:age,:ID)" withParameterDictionary:@{@"name":name,@"age":[NSNumber numberWithInteger:age],@"ID":@(ID)}];
if (result) {
NSLog(@"在事务中insert success");
}
}
}
@catch(NSException *exception) {
//3.在事务中执行任务失败,退回开启事务之前的状态
rollBack = YES;
[db rollback];
}
@finally {
//4\. 在事务中执行任务成功之后
rollBack = NO;
[db commit];
}
NSDate *end = [NSDate date];
NSTimeInterval time = [end timeIntervalSinceDate:begin];
NSLog(@"在事务中执行插入任务 所需要的时间 = %f",time);
}
未使用事务执行一系列操作
-(void)handleNotransaction:(UIButton *)sender {
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath = [documentPath stringByAppendingPathComponent:@"test1.db"];
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
[db open];
if (![db isOpen]) {
return;
}
BOOL result = [db executeUpdate:@"create table if not exists text2('ID' INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,age INTRGER)"];
if (!result) {
[db close];
}
NSDate *begin = [NSDate date];
for (int i = 0; i< 500; i++) {
NSString *name = [NSString stringWithFormat:@"text_%d",i];
NSInteger age = i;
NSInteger ID = i *1000;
BOOL result = [db executeUpdate:@"insert into text2(name,age,ID) values(:name,:age,:ID)" withParameterDictionary:@{@"name":name,@"age":[NSNumber numberWithInteger:age],@"ID":@(ID)}];
if (result) {
NSLog(@"不在事务中insert success");
}
}
NSDate *end = [NSDate date];
NSTimeInterval time = [end timeIntervalSinceDate:begin];
NSLog(@"不在事务中执行插入任务 所需要的时间 = %f",time);
}
比较结果如下:
在事务中执行插入任务 所需要的时间 = 0.426221
不在事务中执行插入任务 所需要的时间 = 0.790417
#import "QXMSqliteManager.h"
@implementation QXMSqliteManager
+ (instancetype)shareManager
{
static QXMSqliteManager *_instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[QXMSqliteManager alloc] init];
});
return _instance;
}
FMDatabase *_db;
- (void)save:(id)object sqlPathDocuments:(NSString *)sqlPathDocuments tableName:(NSString *)tableName mainKey:(NSString *)key pageNum:(NSInteger)pageNum clearTable:(BOOL)clear
{
NSString *sqlPath = [[NSString stringWithFormat:@"%@.sqlite",sqlPathDocuments] appendDocumentDir];
_db = [FMDatabase databaseWithPath:sqlPath];
[_db open];
if ([_db open]) {
NSString *KEY1 = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER NOT NULL,data BLOB NOT NULL,PRIMARY KEY (%@));", tableName, key,key];
BOOL res = [_db executeUpdate:KEY1];
// BOOL res = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_status (id INTEGER PRIMARY KEY AUTOINCREMENT, pageNum integer PRIMARY KEY AUTOINCREMENT,data BLOB NOT NULL);"];
if(res){
CKLog(@"创表执行成功");
}else{
CKLog(@"创表执行失败");
}
}else{
return;
}
if (clear) {
BOOL dele1 = [_db executeUpdate:[NSString stringWithFormat:@"DELETE FROM %@", tableName]];
if(dele1){
CKLog(@"清表成功");
}else{
CKLog(@"清表失败");
}
}
if ([NSJSONSerialization isValidJSONObject:object]) {
// 2.转换为二进制
NSData *data = [NSJSONSerialization
dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:NULL];
// 注意: 在FMDB中可以想字符串拼接一样, 利用?作为占位符. 以后在后面拼接需要的数据
NSString *updateStr = [NSString stringWithFormat:@"insert into %@ ( data ) values (?);", tableName];
BOOL res2 = [_db executeUpdate:updateStr, data];
if(res2){
CKLog(@"添加数据成功");
}else{
CKLog(@"添加数据失败");
}
} else {
CKLog(@"转换失败");
}
[_db close];
}
- (id)readFMDBSqlPathDocuments:(NSString *)sqlPathDocuments tableName:(NSString *)tableName key:(NSString *)key pageNum:(int )pageNum
{
NSString *sqlPath = [[NSString stringWithFormat:@"%@.sqlite",sqlPathDocuments] appendDocumentDir];
_db = [FMDatabase databaseWithPath:sqlPath];
id object;
[_db open];
if ([_db open]) {
// 1.从数据库中查询数据
FMResultSet *set = nil;
NSString *str1 = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = %d;", tableName,key,pageNum];
set =[_db executeQuery:str1];
// set =[_db executeQuery:@"SELECT sum FROM t_status;"];
while ([set next]) {
// 1.取出存储的二进制数据
NSData *data = [set dataForColumn:@"data"];
// 2.将二进制转换为字典
object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
// 3.利用框架将字典转换为模型
// CKLog(@"===11==%@===",object);
return object;
}
}
[_db close];
return object;
}
用法
#pragma mark - 数据库缓存======================
static NSString *const QXMsqlDBName = @"QXM";//数据库名称
static NSString *const QXMstartInfoMainKey = @"pageNum";//主键
static NSString *const QXMStartInfoTbleName_OptionalUnlogin = @"QXMStartInfoTbleName_OptionalUnlogin";//自选未登录缓存数组表名称
#pragma mark - 缓存保存未登录资产-FMDB数据库
+ (void)saveFMDBUnloginOptionalData:(id)responseObject data:(NSDictionary*)data{
[[QXMSqliteManager shareManager] save:responseObject sqlPathDocuments:QXMsqlDBName tableName:QXMStartInfoTbleName_OptionalUnlogin mainKey:QXMstartInfoMainKey pageNum:1 clearTable:YES];
}
#pragma mark - 读取存未登录资产-FMDB数据库
+ (NSArray *)readFMDBUnloginOptionalData:(id)responseObject data:(NSDictionary*)data{
return [[QXMSqliteManager shareManager] readFMDBSqlPathDocuments:QXMsqlDBName tableName:QXMStartInfoTbleName_OptionalUnlogin key:QXMstartInfoMainKey pageNum:1];
}
https://www.jianshu.com/p/8b469f9c9ad3
https://www.jianshu.com/p/7ac1c6eb63ed