Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: SQL rawQuery with wildcard (%)

I'm having a rawQuery() with following sql string similar to this:

selectionArgs = new String[] { searchString };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);

but now I have to include a wildcard in my search, so my query looks something like this:

SELECT column FROM table WHERE column LIKE 'searchstring%'

But when the query contains single quotes the following SQLite Exception is thrown: android.database.sqlite.SQLiteException: bind or column index out of range

How can I run a rawQuery with selectionArgs inside a SQL query with wildcard elements?

like image 416
whlk Avatar asked May 09 '11 09:05

whlk


1 Answers

The Sqlite framework automatically puts single-quotes around the ? character internally.

String [] selectionArgs = {searchString + "%"};
Cursor c;
// Wrap the next line in try-catch
c = db.rawQuery("SELECT column FROM table WHERE like ?", selectionArgs);

That's it.

like image 174
Brad Hein Avatar answered Oct 04 '22 04:10

Brad Hein