Is it possible to pass an array to a SELECT … WHERE … IN statement via FMDB? I tried to implode the array like this:
NSArray *mergeIds; // An array with NSNumber Objects
NSString *mergeIdString = [mergeIds componentsJoinedByString:@","];
NSString *query = @"SELECT * FROM items WHERE last_merge_id IN (?)";
FMResultSet *result = [database executeQuery:query, mergeIdString];
This only works if there is exactly 1 object in the array, which leads me to believe that FMDB adds quotes around the whole imploded string.
So I tried passing the array as is to FMDB's method:
NSArray *mergeIds; // An array with NSNumber Objects
NSString *query = @"SELECT * FROM items WHERE last_merge_id IN (?)";
FMResultSet *result = [database executeQuery:query, mergeIds];
Which doesn't work at all.
I didn't find anything about it in the README or the samples on FMDB's github page.
Thanks, Stefan
If the keys are strings, I use the following code to generate the SQL command:
(assume strArray is an NSArray containing NSString elements)
Please note: if any elements in strArray could potentially contain the "double quote" symbols, you need to write extra codes (before these 2 lines) to escape them by writing 2 double quotes instead.
Adding onto Wayne Liu, if you know that the strings do not contain single or double quotes, you could simply do:
Here's a Swift extension for FMDatabase that breaks array query parameters into multiple named parameters.
Example:
I created a simple FMDB extension to solve the problem:
FMDB+InOperator on GitHub
Well I guess I have to use
executeQueryWithFormat
(which, according to FMDB documentation is not the recommended way). Anyway, here's my solution: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:
Then use the
executeQuery:withArgumentsInArray
call: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.