前言: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<count; i++) {
//如果是text类型
if (column_type == SQLITE_TEXT) {
[dic setValue:column_value_text forKeyPath:column_name];
}
if (column_type == SQLITE_INTEGER) {
[NSString stringWithFormat:@"%d",sqlite3_column_int(stmt, i)];
[dic setValue:column_value_int forKeyPath:column_name];
}
if (column_type == SQLITE_NULL) {
[dic setValue:column_value_null forKeyPath:column_name];
}
}
[mArray addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
if (mArray.count ) {
NSLog(@"存在这个字段");
return YES;
}else{
return NO;
}
}
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 地址:数据库的基本操作
网友评论