码迷,mamicode.com
首页 > 数据库 > 详细

sqlite事务处理

时间:2015-09-07 12:40:50      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

//插入批量数据,可启用事务
- (void)insertDataWithCount:(NSInteger)count isUseTransaction:(BOOL)isUse{
    if (isUse) {
        //手动启用事务
        BOOL isError = NO;
        @try {
         //写可能出现异常的代码
            [_dataBase beginTransaction];//手动开启一个事务
            for (int i=0; i<count; i++) {
                NSString *idStr =[NSString stringWithFormat:@"%d",i];
                NSString *stName = [NSString stringWithFormat:@"student%d",i];
                NSString *insertSql = @"insert into student(id,name) values(?,?)";
                if (![_dataBase executeUpdate:insertSql,idStr,stName]) {
                    NSLog(@"insert error:%@",_dataBase.lastErrorMessage);
                }
            }
        }
        @catch (NSException *exception) {
          //捕获到异常
            NSLog(@"error:%@",exception.reason);
            isError = YES;
            [_dataBase rollback];//回滚,回到最初的状态
        }
        @finally {
           //无论有没有异常,代码都会执行到此处
            if (isError==NO) {
                [_dataBase commit];//提交事务,让批量操作生效
            }
        }
    }else{
       //常规操作
        for (int i=0; i<count; i++) {
            NSString *idStr =[NSString stringWithFormat:@"%d",i];
            NSString *stName = [NSString stringWithFormat:@"student%d",i];
            NSString *insertSql = @"insert into student(id,name) values(?,?)";
            if (![_dataBase executeUpdate:insertSql,idStr,stName]) {
                NSLog(@"insert error:%@",_dataBase.lastErrorMessage);
            }
        }
    }
}

sqlite事务处理

标签:

原文地址:http://www.cnblogs.com/liaods/p/4788472.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!