I keep trying to use wildcards in a search in an android app, and keep running into errors.
I'm performing a search on my application using the string below:
Cursor c_name = b.query("namedrxns", new String[] { "_id", "name" },
"name LIKE %?%", new String[] { query }, null, null, null);
when I use name LIKE %?%
or name=%?%
I get a "near "%": syntax error: , while compiling: SELECT _id, name FROM namedrxns WHERE name=%?%" error.
but with name LIKE '%?%'
or name='%?%'
I get instead "bind or column index out of range: handle 0x40cb70"
Could someone please tell me what I'm doing wrong?
Thanks!
SQLite provides two wildcards for constructing patterns. They are percent sign % and underscore _ : The percent sign % wildcard matches any sequence of zero or more characters. The underscore _ wildcard matches any single character.
For one thing, databases vary considerably in how they handle text; for example, while some databases are case-sensitive by default (e.g. Sqlite, PostgreSQL), others are case-insensitive (SQL Server, MySQL).
In SQLite, a comment that starts with /* symbol and ends with */ and can be anywhere in your SQL statement. This method of commenting can span several lines within your SQL.
The SQLite quote() function allows you to escape a string so that it's suitable for inclusion in an SQL statement. Strings are surrounded by single-quotes with escapes on interior quotes. BLOBs are encoded as hexadecimal literals.
Append the %
to the query
parameter.
I.E.:
Cursor c_name = b.query("namedrxns", new String[] { "_id", "name" },
"name LIKE ?", new String[] { "%"+query+"%" }, null, null, null);
Like Thomas Mueller already said, please note that %
and _
within the value still work as wildcards.
The following should work (but I didn't test it with SQLite):
"name LIKE '%' || ? || '%'"
Please note that "%" and "_" within the value still work as wildcards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With