在iOS中新版本更新涉及字段改动时有发生,为保留原有数据完成数据更新,可以采用一下代码
- (void)alterItemTableToAddFilterColumnsIfNeeded {
[self alterItemTableToAddFilterColunm:@"Color"];
[self alterItemTableToAddFilterColunm:@"FashionStyle"];
[self alterItemTableToAddFilterColunm:@"Category"];
}
- (void)alterItemTableToAddFilterColunm:(NSString *)columnName {
//没有添加该列则修改添加
if (![self checkFilterColumnExists:columnName]) {
[self alterItemTableToAddColumn:columnName];
}
}
- (BOOL)checkFilterColumnExists:(NSString *)columnName {
__block BOOL returnBool = NO;
[_queue inDatabase:^(FMDatabase *db) {
[db open];
FMResultSet *resultSet = [db executeQuery:[NSString stringWithFormat:@"PRAGMA table_info(%@)", @"Item"]];
NSMutableArray* columnNames = [[NSMutableArray alloc] init];
while ([resultSet next]) {
if ([[resultSet stringForColumn:@"name"] isEqualToString: columnName]) {
returnBool = YES;
break;
}
}
[db close];
}];
return returnBool;
}
- (void)alterItemTableToAddColumn:(NSString *)columnName {
NSString *alterSql = [NSString stringWithFormat:@"ALTER TABLE Item ADD COLUMN %@ TEXT DEFAULT ''", columnName, nil];
[_queue inDatabase:^(FMDatabase *db) {
[db open];
if ([db executeUpdate:alterSql]) {
NSLog(@"Alter Item Filter Success!");
} else {
NSLog(@"Alter Item Filter Error!");
}
[db close];
}];
}
网友评论