Search code examples
iossqlitefmdb

How to query SQlite with integer param in iOS using FMDB?


I am trying to query a row which has a string in a particular column. However, I am unable to get the desired result.

Code:

 [_database open];
FMResultSet *results = [_database executeQuery:@"select * from testNotes where notesid=%d",notesID];
NSString *notes=[results stringForColumn:@"notes"];

if ([_database hadError]) {
    NSLog(@"DB Error %d: %@", [_database  lastErrorCode], [_database lastErrorMessage]);
}

[_database close];

I checked the data using sqlite browser. The value I'm sending is 13, and the data exists in the table.

When I use: notesid=%d the console says: (Here FMResultsSet is nil, notes is nil )

DB Error 1: near "%": syntax error

I also tried by giving a space in between = and %d

When I use: notesid='%d' the console says:(Here FMResultsSet is not nil, notes is nil)

DB Error 25: bind or column index out of range

And When I use: notesid='?' the console says

DB Error 25: bind or column index out of range

And when I use: notesid=? the app is crashed at the obj = va_arg(args, id); in FMDatabse.m file

I also tried this:

[_database executeQuery:[NSString stringWithFormat:@"select * from testNotes where notesid='%d'",notesID]];

What is the proper way to query a row based on integer value ?


Solution

  • executeQuery expects all arguments to be Objective-C objects. However, notesID is an integer and thus not an object. In order to fix this, you'll need to wrap notesID in an NSNumber object like this:

    FMResultSet *results = [_database executeQuery:@"select * from testNotes where notesid=?", @(notesID)];