nOOb iOS
nOOb iOS

Reputation: 1394

How to form a LIKE statement in SQLITE with a parameter in iphone iOS?

Say, I have a searchfield called name. If the user types 'John' in the searchfield I should check the 'Name' field for the value "John" and select all the corresponding field values. 'John' will be of NSString which is got from searchBar.text, and it has to be added as parameter to the query. I structured a sql statement like this which never worked.

NSString *query = [NSString stringWithFormat:@"select * from Employee where EmployeeName LIKE '%%@%'", searchText.text];
const char *sqlStatement = [query UTF8String];

I tried this also

NSString *query = [NSString stringWithFormat:@"select * from Employee where EmployeeName LIKE %'%@'%", searchText.text];
const char *sqlStatement = [query UTF8String];

Nothing worked.

Upvotes: 4

Views: 8200

Answers (2)

nOOb iOS
nOOb iOS

Reputation: 1394

I tried all possible ways, but the exact query was not forming and finally made it this way. Its round about method, but works fine.

NSString *query = [NSString stringWithFormat:@"select * from Employee where EmployeeName LIKE"];
query = [query stringByAppendingString:@" '%"];
NSString  *addParameter = [NSString stringWithFormat:@"%@",searchText];
query = [query stringByAppendingString:addParameter];
query = [query stringByAppendingString:@"%'"];

This feels bit lengthy code, but works fine.

And thanks @danh for this wonderful answer. Now, I can replace four lines of my code into single line..

Upvotes: 1

danh
danh

Reputation: 62676

The trick is to get the percents in there. It's awkward, but you can do it like this:

@"select * from Employee where EmployeeName LIKE '%%%@%%'"

%% is a percent, %@ is the substitution string.

Upvotes: 28

Related Questions