Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard not working in SQLite

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!

like image 552
Alex Curran Avatar asked Aug 28 '10 23:08

Alex Curran


People also ask

What is wildcard in SQLite?

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.

Is SQLite case sensitive?

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).

How do I comment in SQLite?

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.

How do I escape in SQLite?

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.


2 Answers

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.

like image 133
whlk Avatar answered Sep 19 '22 19:09

whlk


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.

like image 42
Thomas Mueller Avatar answered Sep 22 '22 19:09

Thomas Mueller