Fmdb 选择带有变量表名的查询
Posted
技术标签:
【中文标题】Fmdb 选择带有变量表名的查询【英文标题】:Fmdb Select query with variable table name 【发布时间】:2013-09-30 13:28:03 【问题描述】:我想从不同的表中获取结果,表是由用户选择的。所以,我使用表名作为变量,但它返回 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】:使用此代码:
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]]];
【讨论】:
谢谢@Vin。这是为此目的的正确/优化查询吗?以上是关于Fmdb 选择带有变量表名的查询的主要内容,如果未能解决你的问题,请参考以下文章