Escaping sqlite string in obj-c

iPhone Add comments

Problem adding "%" inside your sql queries? read below.

const char *sqlStatement = "select fname,lname from students where lname like ?001 and fname like ?002";

Notice that the parameter tokens, ?001 and ?002 do not have quotes around them.
This statement needs to be prepared in the usual way.

NSString *fnameSearch = [NSString stringWithFormat:@"%%%@%%", fnameSearchWord];

NSString *lnameSearch = [NSString stringWithFormat:@"%%%@%%", lnameSearchWord];

 

Notice the %% characters in the format string. This results in one % in the output string.
%@ is the replacement token for your string parameter.  
Finally, you have to bind your strings to the prepared statement like this:

 

sqlite3_stmt *compiledStatement;

if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK

{

  sqlite3_bind_text(compiledStatement, 1, [fnameSearchWord UTF8String], -1, SQLITE_STATIC);

  sqlite3_bind_text(compiledStatement, 2, [lnameSearchWord UTF8String], -1SQLITE_STATIC);

while(sqlite3_step(compiledStatement) == SQLITE_ROW)

{

// continue data manipulation here.

 }

}