Created
September 10, 2018 07:04
-
-
Save wzshare/493f8148e871eeec9487e784938e2ed3 to your computer and use it in GitHub Desktop.
FMDB Transaction Usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)handleTransaction:(UIButton *)sender { | |
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; | |
NSString *dbPath = [documentPath stringByAppendingPathComponent:@"test1.db"]; | |
FMDatabase *db = [[FMDatabase alloc]initWithPath:dbPath]; | |
if (![db open]) { | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment