使用FMDB事务批量更新数据,速度会有大幅度提升。
下面的例子中可以看到,不使用事务,更新374条数据就用了6秒多;而使用事务,仅用了300多毫秒。(iPhone6测试)
不使用事务
FMDatabaseQueue * dbQueue = [SGVFoundationDataCenter shareInstance].dbQueue;
[dbQueue inDatabase:^(FMDatabase *db) {
// 清除数据
NSLog(@"-- add Station begin count = %ld",stations.count);
[db executeUpdate:@"delete from sgv_station where city_code = ?",@(cityCode)];
[stations enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
SGVSubwayStation * station = obj;
[db executeUpdate:@"INSERT INTO sgv_station (city_code, line_code, station_code, station_name, line_inner_code, is_wifi_valid) VALUES (?,?,?,?,?,?)",@(cityCode), @(station.lineCode),@(station.stationCode), station.stationName, @(station.lineInnerCode),@(station.isWiFiValid)];
}];
NSLog(@"-- add Station end"];
}];
使用事务
FMDatabaseQueue * dbQueue = [SGVFoundationDataCenter shareInstance].dbQueue;
[dbQueue inDatabase:^(FMDatabase *db) {
// 清除数据
NSLog(@"-- add Station begin count = %ld",stations.count);
[db beginTransaction];
[db executeUpdate:@"delete from sgv_station where city_code = ?",@(cityCode)];
[stations enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
SGVSubwayStation * station = obj;
[db executeUpdate:@"INSERT INTO sgv_station (city_code, line_code, station_code, station_name, line_inner_code, is_wifi_valid) VALUES (?,?,?,?,?,?)",@(cityCode), @(station.lineCode),@(station.stationCode), station.stationName, @(station.lineInnerCode),@(station.isWiFiValid)];
}];
[db commit];
NSLog(@"-- add Station end"];
}];