sqlite事务处理

 1 //插入批量数据,可启用事务
 2 - (void)insertDataWithCount:(NSInteger)count isUseTransaction:(BOOL)isUse{
 3     if (isUse) {
 4         //手动启用事务
 5         BOOL isError = NO;
 6         @try {
 7          //写可能出现异常的代码
 8             [_dataBase beginTransaction];//手动开启一个事务
 9             for (int i=0; i<count; i++) {
10                 NSString *idStr =[NSString stringWithFormat:@"%d",i];
11                 NSString *stName = [NSString stringWithFormat:@"student%d",i];
12                 NSString *insertSql = @"insert into student(id,name) values(?,?)";
13                 if (![_dataBase executeUpdate:insertSql,idStr,stName]) {
14                     NSLog(@"insert error:%@",_dataBase.lastErrorMessage);
15                 }
16             }
17         }
18         @catch (NSException *exception) {
19           //捕获到异常
20             NSLog(@"error:%@",exception.reason);
21             isError = YES;
22             [_dataBase rollback];//回滚,回到最初的状态
23         }
24         @finally {
25            //无论有没有异常,代码都会执行到此处
26             if (isError==NO) {
27                 [_dataBase commit];//提交事务,让批量操作生效
28             }
29         }
30     }else{
31        //常规操作
32         for (int i=0; i<count; i++) {
33             NSString *idStr =[NSString stringWithFormat:@"%d",i];
34             NSString *stName = [NSString stringWithFormat:@"student%d",i];
35             NSString *insertSql = @"insert into student(id,name) values(?,?)";
36             if (![_dataBase executeUpdate:insertSql,idStr,stName]) {
37                 NSLog(@"insert error:%@",_dataBase.lastErrorMessage);
38             }
39         }
40     }
41 }

 

posted on 2015-09-07 11:50  Baymax01  阅读(233)  评论(0编辑  收藏  举报

导航