Batch update of fmdb transaction in IOS

Time:2021-2-23

This example for you to share the IOS fmdb transaction batch update data, for your reference, the specific content is as follows

Open database (SQLite)

///Open database
+ (BOOL)openDataBase{
  
  _TYDatabase = [[FMDatabase alloc]initWithPath:[self databasePath]];
  if ([_TYDatabase open]) {
    return YES;
  }
  return NO;
}
///Database path
+ (NSString *)databasePath{
  NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  NSString *dataPath = [documentPath stringByAppendingPathComponent:@"TY.SQLite"];
  NSFileManager *fileM = [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;
  
}

affair

/**
 affair
 Arraysql: SQL statement array
 */
- (void)beginTransaction:(NSArray *)arraySql;
{
  //// static FMDatabase *_TYDatabase = nil;
  BOOL isOpen=[_TYDatabase open];
  if (!isOpen) {
    Nslog (@ "failed to open database! ");
    return;
  }
  ///Start things
  [_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;
    ///Rollback
    [_TYDatabase rollback];
  }
  @finally {
    if (!isRollBack) {
      ///Submit
      [_TYDatabase commit];
    }
  }
  [_TYDatabase close];
}

Multithreaded transaction

/**
 Multithreaded 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 (@ "success");
    }
  }];
}

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.