iOS FMDB 事务操作
2017-09-06 本文已影响538人
dy_zhang
最近又用到了FMDB,对事务操作有了更深刻的认识。sqlite 本身是支持事务操作的,FMDB 作为对 sqlite 的封装也是支持的。那什么是事务操作?简单讲一次 executeUpdate (插入数据,本质是 sqlite3_exec)就是一次事务操作,其具体过程是:开始新事务-->插入数据-->提交事务。我们向数据库中插入多少条数据,这个过程就会执行多少次,显然当插入的数据很多的时候这是非常耗时的。就比如你订了外卖,今天特别饿点了8个菜,结果外卖小哥 freestyle 做好一个菜送一个菜,mmp!你是不是要崩溃了

大家知道真实的情况是外卖小哥会吧饭菜一次性送给你。
所以事务操作的原理就是:所有任务执行完成后再将结果一次性提交到数据库。
举个🌰大家看一下:
有个 Person 类,它有如下信息:

把 Person 信息保存到数据库,作为对比,同样的数据量(10000组)一个开启事操作另一个不开启:

对比结果如下(注:模拟器运行):

从上面的时间看使用事务操作要比不使用节省大量时间,尤其当数据非常多的时候更应该使用事务操作来处理,避免重复的步骤浪费时间。

使用事务操作的代码(FMDB):
// 插入数据
- (void)insertData:(id)data isTransaction:(BOOL)isTransaction {
BOOL isOpen = [_database open];
if (isOpen) {
if (isTransaction) {
//NSLog(@"**********开始事务操作*************");
[_database shouldCacheStatements]; // 开启缓存
[_database beginTransaction]; // 事务操作
BOOL isRollBack = NO;
@try {
[self performInsertWithData:data];
}
@catch (NSException *exception) {
isRollBack = YES;
[_database rollback]; // 回滚
}
@finally {
if (!isRollBack) {
[_database commit];
}
}
}else {
[self performInsertWithData:data];
}
[_database close];
}
}
- (void)performInsertWithData:(id)data {
NSArray *arr = (NSArray *)data;
BOOL isInsert = NO;
for (PersonModel *model in arr) {
NSString *sql = [NSString stringWithFormat:@"insert into %@ values(NULL,'%@',%ld,'%@','%@')",@"PersonClass",model.name,model.age,model.gender,model.role];
isInsert = [_database executeUpdate:sql];
//NSLog(@"%@",isInsert ? @"插入成功":@"插入失败");
}
}
注:isTransaction 是否使用事务操作