一.根據(jù)表名刪除數(shù)據(jù)表
- (BOOL)clearDB
{
if (self.dataBase == nil || !self.dataBase.open)
{
DLog(@"--db打開錯誤--");
return NO;
}
//1.查詢所有表名稱
NSString *sql = [NSString stringWithFormat:@"SELECT name FROM sqlite_master WHERE type='table' order by name"];
FMResultSet *rs = [self.dataBase executeQuery:sql];
NSMutableArray *tableNames = [NSMutableArray array];
while (rs &&[rs next])
{
NSString *tableName =[rs stringForColumn:@"name"];
[tableNames addObject:tableName];
}
//2.過濾不刪除的表名
NSString * saveTableName1 = [NSString stringWithFormat:@"LoginData"];
// NSString * saveTableName2 = [NSString stringWithFormat:@"PushMessage"];
// NSString * saveTableName3 = [NSString stringWithFormat:@"Notice"];
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != %@ && SELF != %@ && SELF != %@",saveTableName1,saveTableName2,saveTableName3];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != %@ ",saveTableName1];
NSArray *delNames = [tableNames filteredArrayUsingPredicate:predicate];
__block BOOL ret;
[delNames enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj && [obj isKindOfClass:[NSString class]]) {
NSString *delSqlStr = [NSString stringWithFormat:@"DROP TABLE IF EXISTS %@;",obj];
DLog(@"-delSqlStr--%@",delSqlStr);
ret = [self.dataBase executeUpdate:delSqlStr];
[rs close];
}
}];
return ret;
}
二,數(shù)據(jù)庫添加新字段
#pragma mark 存儲新的字段 updatetime;
+(void)addNewColumn
{
XKDataBase *dbHandler = [XKDataBase shared];
if (![dbHandler openDB]) {
return ;
}
if (![dbHandler.dataBase tableExists:@"Notice"]) {
DLog(@"Notice表不存在");
return ;
}
NSMutableArray *tmpArray = [NSMutableArray array];
FMResultSet *rs = [dbHandler.dataBase executeQuery:@"pragma table_info([Notice]) "];
while ([rs next]) {
NSString *culmnName = [rs stringForColumnIndex:1];
[tmpArray addObject:culmnName];
}
[rs close];
if (![tmpArray containsObject:@"updatetime"]) {
NSString *sql = [NSString stringWithFormat:@"ALTER TABLE Notice ADD COLUMN updatetime int"];
BOOL ret = [dbHandler.dataBase executeUpdate:sql];
DLog(@"插入updatetime ret = %d",ret);
}
}
三.檢查表中 是否含有某個字段
+(BOOL)checkTable:(NSString *)tableName comtainColumn:(NSString*)columnName
{
XKDataBase *dbHandler = [XKDataBase shared];
if (![dbHandler openDB]) {
DLog(@"數(shù)據(jù)庫未打開");
return YES;
}
if (![dbHandler.dataBase tableExists:tableName]) {
DLog(@"checkUpdatetimeColumn %@表不存在",tableName);
return YES;
}
NSString *sql = [NSString stringWithFormat:@"pragma table_info([%@])",tableName];
NSMutableArray *tmpArray = [NSMutableArray array];
FMResultSet *rs = [dbHandler.dataBase executeQuery:sql];
while ([rs next]) {
NSString *culmnName = [rs stringForColumnIndex:1];
[tmpArray addObject:culmnName];
}
[rs close];
//包含字段
if ([tmpArray containsObject:columnName]) {
return YES;
}else
{
return NO;
}
}```