Sqlite判断数据库表是否有某个字段

前言:Sqlite在数据库升级时需要判断某个字段是否存在,不存在插入(FMDB有自己的判断方法,只说明Sqlite的使用)

1、判断某个字段是否存在

select * from sqlite_master where name='表名' and sql like '%字段名%`

比如:select * from sqlite_master where name='user' and sql like '%modelNumber%'
方法如下

///检查是表中是否有某个字段
+(BOOL)checkHaveColumn:(NSString *)column{
    sqlite3 *db = [DBDatebase open];
    NSString *sql = [NSString stringWithFormat:@"select * from sqlite_master where name='user' and sql like '%%%@%%'",column];
//           NSString * sql = @"select * from sqlite_master where name='user' and sql like '%enterPrisede%'";
    //查询的句柄,游标
    sqlite3_stmt * stmt;
    NSMutableArray *mArray = [NSMutableArray array];
    
    if (sqlite3_prepare_v2(db, sql.UTF8String, -1, &stmt, NULL) == SQLITE_OK) {
        //查询数据
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            //获取查询了多少列
            int count = sqlite3_column_count(stmt);
            //创建字典
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            
            for (int i = 0; i

2、添加字段

ALTER TABLE user ADD COLUMN '字段名' text

ALTER TABLE user ADD COLUMN 'name' text

///表中添加字段
+(void)addCloumnWith:(NSString *)column{
    BOOL have =  [self checkHaveColumn:column];
    if (!have) {
        sqlite3 *db = [DBDatebase open];
        NSString * sql = [NSString stringWithFormat:@"ALTER TABLE user ADD COLUMN '%@' text",column];
        //执行创建表的sql语句
        char *error = nil;
        int db_exec = sqlite3_exec(db, [sql UTF8String], NULL, NULL, &error) ;
        if (db_exec == SQLITE_OK) {
            NSLog(@"插入字段成功");
        }else{
            NSLog(@"插入字段失败");
        }
        sqlite3_close(db);
    }
    
}

demo 地址:数据库的基本操作

你可能感兴趣的:(Sqlite判断数据库表是否有某个字段)