一.什么是FMDB?
1.FMDB存在的意义
iOS中使用C语言函数对原生SQLite数据库进行增删改查操作,复杂麻烦,于是,就出现了一系列将SQLite API封装的库,如FMDB
FMDB是针对libsqlite3框架进行封装的三方,它以OC的方式封装了SQLite的C语言的API,使用步骤与SQLite相似
FMDB的优点是:
(1) 使用时面向对象,避免了复杂的C语言代码
(2) 对比苹果自带的Core Data框架,更加轻量级和灵活
(3) 提供多线程安全处理数据库操作方法,保证多线程安全跟数据准确性
2.FMDB缺点:
(1) 因为是OC语言开发,只能在iOS平台上使用,所以实现跨平台操作时存在限制性
FMDB 在Git上的下载链接地址:https://github.com/ccgus/fmdb
3.FMDB使用方式
(1) GItHub中下载FMDB,将文件导入工程中
(2) 导入libsqlite3.0框架,导入头文件FMDatabase.h
(3) 创建数据库路径,创建数据库,操作前开启数据库,构建操作SQLite语句,数据库执行增删改查操作,操作完关闭数据库
4.FMDB基本使用示例:
@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);
}
网友评论