Fmdb选择具有变量表名的查询

时间:2013-09-30 13:28:04

标签: iphone ios sqlite xcode5 fmdb

我想从不同的表中获取结果,用户选择表。所以,我使用表名作为变量,但它返回nil查询。

FMResultSet *query = [db1 executeQuery:@"SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'", [NSString stringWithFormat:@"%@1",tableName], [NSString stringWithFormat:@"%@2",tableName],
[NSString stringWithFormat:@"%@3",tableName], [NSString stringWithFormat:@"%@4",tableName], [NSString stringWithFormat:@"%@5",tableName], [NSString stringWithFormat:@"%@6",tableName]];

如果我对表名进行硬编码,则返回数据。

FMResultSet *query = [db1 executeQuery:
@"SELECT Image, Explanation FROM Class1 WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM Class2 WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM Class3 WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM Class4 WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM Class5 WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM Class6 WHERE Image !='empty'"];

我记录了tableName值,它返回了正确的值,即“Class”。 请帮我解决这个问题,并为此目的提出最佳查询。

1 个答案:

答案 0 :(得分:0)

使用此代码:

FMResultSet *query = [db1 executeQuery:[NSString stringWithFormat:@"SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'"
"UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'", [NSString stringWithFormat:@"%@1",tableName], [NSString stringWithFormat:@"%@2",tableName],
[NSString stringWithFormat:@"%@3",tableName], [NSString stringWithFormat:@"%@4",tableName], [NSString stringWithFormat:@"%@5",tableName], [NSString stringWithFormat:@"%@6",tableName]]];