iOS FMDB 查詢 批量更新

躍然發表於2015-08-13
+ (NSMutableArray *)querygoodsByIdFromLocal:(NSString *)dayFlightId{
    FMDatabase *fmdb = [SADBManager sharedDB];
    if (!fmdb) {
        //失敗處理
        return nil;
    }
    //編寫SQL查詢語句
    NSString *query = [NSString stringWithFormat:@"select * from FlightGoods where dayFlightId= '%@'", dayFlightId];
    
    FMResultSet *rs = [fmdb executeQuery:query];
    
    NSMutableArray *invArray = [[NSMutableArray alloc]init];
    FlightGoods *flightgoods;
    
    while ([rs next]) {
        flightgoods = [[FlightGoods alloc]init];

        flightgoods.dayFlightId = [rs stringForColumn:@"dayFlightId"];
        flightgoods.goodsCode = [rs stringForColumn:@"goodsCode"];
        flightgoods.goodsName = [rs stringForColumn:@"goodsName"];
        flightgoods.goodsUnit = [rs stringForColumn:@"goodsUnit"];
        flightgoods.remarks = [rs stringForColumn:@"remarks"];
        flightgoods.cabinStockNum = [[NSNumber alloc]initWithInt:[rs intForColumn:@"cabinStockNum"]];
        flightgoods.loseNum = [[NSNumber alloc]initWithInt:[rs intForColumn:@"loseNum"]];
        flightgoods.actualNum = [[NSNumber alloc]initWithInt:[rs intForColumn:@"actualNum"]];
        flightgoods.tempActualNum = flightgoods.actualNum;// 這裡為tempActualNum賦值,之後根據這個值判斷能否加1操作
        flightgoods.tempLoseNum = flightgoods.loseNum;
        flightgoods.tempRemarks = flightgoods.remarks;
        
        [invArray addObject:flightgoods];
    }
    return invArray;
}

// 更新物件值到資料庫
+ (BOOL)updateGoodsByFlightGoods:(NSMutableArray *)flightGoodsArr{
    FMDatabase *fmdb = [SADBManager sharedDB];
    if (!fmdb) {
        //失敗處理
        return nil;
    }
    
    [fmdb beginTransaction];
    BOOL isRollBack = NO;
    @try {
        for (int i = 0; i<[flightGoodsArr count]; i++) {
            
            FlightGoods * flightGoods = [flightGoodsArr objectAtIndex:i];
            NSString * update = [NSString stringWithFormat:@"update FlightGoods set actualNum = '%@', loseNum = '%@',remarks = '%@' where goodsCode = '%@'",flightGoods.actualNum,flightGoods.loseNum,flightGoods.remarks,flightGoods.goodsCode];
            BOOL isSuccess = [fmdb executeUpdate:update];
    
            if (!isSuccess) {
                NSLog(@"update Failure");
            }
        }
    }
    @catch (NSException *exception) {
        isRollBack = YES;
        [fmdb rollback];
    }
    @finally {
        if (!isRollBack) {
            [fmdb commit];
        }
    }
    
    return !isRollBack;

}

相關文章