Passing an array to sqlite WHERE IN clause via FMDB? Passing an array to sqlite WHERE IN clause via FMDB? sqlite sqlite

Passing an array to sqlite WHERE IN clause via FMDB?


I was having the same issue, and I figured it out, at least for my own app. First, structure your query like so, matching the number of question marks as the amount of data in the array:

NSString *getDataSql = @"SELECT * FROM data WHERE dataID IN (?, ?, ?)";

Then use the executeQuery:withArgumentsInArray call:

FMResultSet *results = [database executeQuery:getDataSql withArgumentsInArray:dataIDs];

In my case, I had an array of NSString objects inside the NSArray named dataIDs. I tried all sorts of things to get this SQL query working, and finally with this combination of sql / function call, I was able to get proper results.


Well I guess I have to use executeQueryWithFormat (which, according to FMDB documentation is not the recommended way). Anyway, here's my solution:

NSArray *mergeIds; // An array of NSNumber ObjectsNSString *mergeIdString = [mergeIds componentsJoinedByString:@","];NSString *query = @"SELECT * FROM items WHERE last_merge_id IN (?)";FMResultSet *res = [self.database executeQueryWithFormat:query, mergeIdString];


Adding onto Wayne Liu, if you know that the strings do not contain single or double quotes, you could simply do:

NSString * delimitedString = [strArray componentsJoinedByString:@"','"];NSString * sql = [NSString stringWithFormat:@"SELECT * FROM tableName WHERE fieldName IN ('%@')", delimitedString];