I would like to check if an id list is in the database. Here is my code...
NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
NSString *string = [array componentsJoinedByString:@","];
FMResultSet * rs = [self.db executeQuery:@"SELECT id FROM FriendList WHERE id NOT IN (?)",string];
It's doesn't work. It's only work if array only has a single number.
Anyone knows how to do SELECT NOT IN using FMDB?
Thanks!
You need little modification here.
Follow below code.
NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
NSString *components = [array componentsJoinedByString:@", "];
NSMutableString *valueString = [NSMutableString new];
NSMutableString *fieldString = [NSMutableString new];
[fieldString appendString:@"SELECT id FROM FriendList WHERE id NOT IN ("];
for (NSString *fielValue in array) {
[fieldString appendString:@"?,"];
[valueString appendString:fielValue];
}
[fieldString replaceCharactersInRange:NSMakeRange([fieldString length] - 1, 1) withString:@")"];
NSString *normalString = [NSString stringWithString:fieldString];
fieldString = nil;
FMResultSet * rs = [self.db executeQuery:@"%@", normalString, components];
EDIT:
From the information you provide me in a comments, I did figure out that sqlite
is not able to compile the string literal while you provide multiple items from array components. I modify answer still it's from your end to test that it is working or not? Leave a comment for acknowledgment.