Fmdb Select query with variable table name

陌路散爱 提交于 2019-12-13 06:19:30

问题


I want to get results from different tables, tables are selected by the user. So, I am using table name as variable but it returns nil query.

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]];

If I hardcode the table name it returns the data.

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'"];

I logged the tableName value and it is returning the correct value, which is "Class". Please help me solving this issue and also suggest the best query for this purpose.


回答1:


Use this Code :

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]]];


来源:https://stackoverflow.com/questions/19095519/fmdb-select-query-with-variable-table-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!