13

I am using FMDB, which is a wrapper for SQLite. http://github.com/ccgus/fmdb

Here is my query line:

FMResultSet *athlete = [db executeQuery:@"SELECT * FROM athletes WHERE athlete_name LIKE ?", search_text];

Using this I can get a result back if I type in the exact name of the athlete. But, I'm trying to use LIKE so I can search on the name. But, when I add %?% instead of just ? ... nothing returns. And there are no errors.

Has anyone ran into this before and know what I'm doing wrong?

Thanks everyone!

TheTC
  • 589
  • 7
  • 18

1 Answers1

34

The wildcard characters (%) have to be part of the substituted variable, not the query string:

FMResultSet *rs = [db executeQuery:@"SELECT * FROM athletes WHERE athlete_name LIKE ?",
                  [NSString stringWithFormat:@"%%%@%%", search_text]];
omz
  • 52,281
  • 5
  • 125
  • 139
  • Ah ok ... thank you very much. I'm 1/2 asleep today, so I assumed I was missing something simple. =) – TheTC Jan 25 '12 at 19:40
  • I'm having difficulty getting this to work. Is there an alternative syntax? I'm running out of ideas. – Echilon Jan 26 '12 at 20:33
  • Ah nice!! Thanks @omz. I'm extremely new to mysql so would you mind explaining what the %%%@%% means? I get the %@... but what is the significance of the other %'s? And the ?. I'm assuming the ? is the sql equivalent to %@ but I still get this warning from it: `Data argument not used by format string` – crewshin Aug 04 '12 at 23:53
  • 2
    The `%` is a "wildcard" for the SQL `LIKE` operator. Think of it as a placeholder that allows you to match parts of a string. Because `%` has a special meaning in format strings, each of it is doubled to indicate "I want an actual percent character, not a format string placeholder like `%@`". This is only necessary because I use `stringWithFormat:` here. You're right that the `?` is basically the SQL equivalent of `%@`. – omz Aug 05 '12 at 00:48