ios-FMDB 添加字段,添加自增长

需求:

需要在数据中添加字段,设置字段自增长

实现方式:

1、判断表中是否存在改字段,如果不存在则添加

if (![db columnExists:@"新增字段" inTableWithName:@"表名"]){  
   NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ 
   INTEGER",@"表名",@"新增字段"];  
    BOOL worked = [db executeUpdate:alertStr];  
  if(worked){
    NSLog(@"插入成功");
   }else{
       NSLog(@"插入失败");
   }
}

2、在sqlite表中不支持修改和删除字段

alter table 表名 rename column A to B
alter table 表名 drop column 字段

3、设置自增长" integer primary key AUTOINCREMENT "


 NSString *createSpaceSql = [NSString stringWithFormat:@"create table if not exists  schoolSpace (buss_id integer primary key AUTOINCREMENT,title text,content text,picture_urls text,age int)"];//UNIQUE唯一
[database executeUpdate:createSpaceSql];

//写入数据到数据库
NSString *insertSql = [NSString stringWithFormat:@"insert into schoolSpace (title, content, picture_urls,age) values ('%@','%@','%@',%d)",@"张三",@"femail",@"http://baidu.com",5];
        if (![db executeUpdate:insertSql]) {
            NSLog(@"insert row fail");
            
        }

示例


+ (BOOL)createTable
{
    __block BOOL res = YES;
    JKDBHelper *jkDB = [JKDBHelper shareInstance];
    [jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        NSString *tableName = NSStringFromClass(self.class);
        NSString *columeAndType = [self.class getColumeAndTypeString];
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@);",tableName,columeAndType];
        if (![db executeUpdate:sql]) {
            res = NO;
            *rollback = YES;
            return;
        };
        
        NSMutableArray *columns = [NSMutableArray array];
        FMResultSet *resultSet = [db getTableSchema:tableName];
        while ([resultSet next]) {
            NSString *column = [resultSet stringForColumn:@"name"];
            [columns addObject:column];
        }
        NSDictionary *dict = [self.class getAllProperties];
        NSArray *properties = [dict objectForKey:@"name"];
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",columns];
        //过滤数组
        NSArray *resultArray = [properties filteredArrayUsingPredicate:filterPredicate];
        for (NSString *column in resultArray) {
            NSUInteger index = [properties indexOfObject:column];
            NSString *proType = [[dict objectForKey:@"type"] objectAtIndex:index];
            NSString *fieldSql = [NSString stringWithFormat:@"%@ %@",column,proType];
            NSString *sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@ ",NSStringFromClass(self.class),fieldSql];
            if (![db executeUpdate:sql]) {
                res = NO;
                *rollback = YES;
                return ;
            }
        }
    }];
    
    return res;
}

使用场景:

1、在Model中字段不够用的时候,需要添加字段;
2、欢迎指正、交流。

你可能感兴趣的:(ios-FMDB 添加字段,添加自增长)