標籤:
//插入批量資料,可啟用事務
- (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交易處理