IOS-FMDB transaction [batch update database], ios-fmdb transaction database
Open a database (sqlite)
/// Open the database + (BOOL) openDataBase {_ TYDatabase = [[FMDatabase alloc] initWithPath: [self databasePath]; if ([_ TYDatabase open]) {return YES ;} return NO;} // database path + (NSString *) databasePath {NSString * documentPath = [callback (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString * dataPath = [documentPath stringByAppendingPathComponent: @ "TY. SQLite "]; NSFileManager * f IleM = [NSFileManager defaultManager]; if (! [FileM fileExistsAtPath: dataPath]) {NSString * filePath = [[NSBundle mainBundle] pathForResource: @ "TY" ofType: @ "SQLite"]; [fileM copyItemAtPath: filePath toPath: dataPath error: nil];} NSLog (@ "% @", dataPath); return dataPath ;}
Transactions
/** Transaction arraySql: SQL statement array */-(void) beginTransaction :( NSArray *) arraySql; {// static FMDatabase * _ TYDatabase = nil; BOOL isOpen = [_ TYDatabase open]; if (! IsOpen) {NSLog (@ "failed to open the database! "); Return;} // start transaction [_ TYDatabase beginTransaction]; BOOL isRollBack = NO; @ try {for (int I = 0; I <arraySql. count; I ++) {BOOL result = [_ TYDatabase executeUpdate: arraySql [I]; if (! Result) {NSLog (@ "operation failed [% d] = SQL: % @", I, arraySql [I]) ;}}@ catch (NSException * exception) {isRollBack = YES; // roll back [_ TYDatabase rollback];} @ finally {if (! IsRollBack) {// submit [_ TYDatabase commit] ;}} [_ TYDatabase close];}
Multi-threaded transactions
/** Multi-thread transaction arraySql: SQL statement array */+ (void) beginTransactionT :( NSArray *) arraySql {FMDatabaseQueue * databaseQueue = [FMDatabaseQueue databaseQueueWithPath: [self databasePath]; [databaseQueue inTransaction: ^ (FMDatabase * db, BOOL * rollback) {BOOL result = NO; for (int I = 0; I <arraySql. count; I ++) {result = [_ TYDatabase executeUpdate: arraySql [I];} if (result) {NSLog (@ "successful") ;}}];}