我需要对所有列进行搜索,因此我不想在where子句中指定每个列名,而是创建一个可以搜索所有列的方法.
-(void) fillSomeobjectNames:(NSString *)filter
{
FMDatabase *db = [FMDatabase databaseWithPath:databasePath];
[db open];
NSString *sql = [NSString stringWithFormat:@"SELECT id, name, imagefile FROM %@ %@", mainTableName, filter];
FMResultSet *results = [db executeQuery:sql];
while([results next])
{
Someobject *someobject = [[Someobject alloc] init];
[someobject setID:[results intForColumn:@"id"]];
[someobject setName:[results stringForColumn:@"name"]];
NSString *iconName = [[results stringForColumn:@"imagefile"] stringByReplacingOccurrencesOfString:@".jpg" withString:@""];
[someobject setIconPath:[NSString stringWithFormat:@"%@-ico.jpg",iconName]];
[someobjects someobject];
}
[db close];
}
Run Code Online (Sandbox Code Playgroud)
'filter'可以是'WHERE remark = [searchText] AND description = [searchText]依此类推......
我不认为这可以使用单个SELECT语句完成.PRAGMA table_info(table_name)不幸的是,获取列名的最佳方法是不能在SELECT语句中使用,因此您需要一个额外的SELECT来获取列名,然后您可以构建您的SQL并执行您想要的操作:
-(void) fillSomeobjectNames:(NSString *)filter
{
FMDatabase *db = [FMDatabase databaseWithPath:databasePath];
[db open];
FMResultSet columnNamesSet* = [db executeQuery:[NSString stringWithFormat:@"PRAGMA table_info(%@)", mainTableName]];
NSMutableArray* columnNames = [[NSMutableArray alloc] init];
while ([columnNamesSet next]) {
[columnNames addObject:[columnNamesSet stringForColumn:@"name"]];
}
// put whatever you need to look for as mySearchPhrase
NSString* partToAppend = [NSString stringWithFormat:@"=%@ OR ", @"mySearchPhrase"];
NSString* filter = [columnNames componentsJoinedByString:partToAppend];
filter = [filter stringByAppendingString:[NSString stringWithFormat:@"=%@", @"mySearchPhrase"]];
// now your sql would look like this
NSString *sql = [NSString stringWithFormat:@"SELECT id, name, imagefile FROM %@ WHERE %@", mainTableName, filter];
FMResultSet *results = [db executeQuery:sql];
while([results next])
{
Someobject *someobject = [[Someobject alloc] init];
[someobject setID:[results intForColumn:@"id"]];
[someobject setName:[results stringForColumn:@"name"]];
NSString *iconName = [[results stringForColumn:@"imagefile"] stringByReplacingOccurrencesOfString:@".jpg" withString:@""];
[someobject setIconPath:[NSString stringWithFormat:@"%@-ico.jpg",iconName]];
[someobjects someobject];
}
[db close];
}
Run Code Online (Sandbox Code Playgroud)
请注意,我将WHERE文字移出了过滤器,而且我也使用了OR替代AND,这是我认为你打算做的.
另外要记住的是每列中的数据类型.您将每个字符串与字符串进行比较,但是您的表格中的每一列都是文本类型吗?我使用的pragma语句也返回给定列的类型(在名为type的列中),因此您可以使用它来过滤text类型的列.