views:

49

answers:

1

I'd like to run a LIKE query in sqlite3 with the user's input safely escaped. Basically, I want to do something like this:

char* query = "SELECT * FROM table WHERE LOWER(notes) LIKE '%?%'";
sqlite3_stmt* statement;
sqlite3_prepare_v2( database, query, -1, &statement, NULL );

But the ? is not honored when inside the LIKE expression. Anyone know how to do this?

+4  A: 
char* query = "SELECT * FROM table WHERE LOWER(notes) LIKE '%' || ? || '%'";

But I recommend you look into using FTS3 for full text searching, because your queries will run hundreds of times faster than using brute-force LIKE queries.

Bill Karwin
+1: Oracle and PostgreSQL were the only other DBs I knew of that used double pipes for string concatenation (now ANSI standard too): http://www.sqlite.org/lang_expr.html
OMG Ponies
MySQL supports it too if you set SQL_MODE to `ANSI` or `PIPES_AS_CONCAT`.
Bill Karwin
Awesome! Thanks. The database is a tiny single-user DB, so performance should be adequate.
Bill
+1 for recommending FTS.
Donal Fellows