Reputation: 15635
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?
Upvotes: 10
Views: 14744
Reputation: 1482
Brad Hein's and Mannaz's solution did not work for me, but this did:
String query = "SELECT column FROM table WHERE column=%s";
String q = String.format(query, "\""+searchString + "%\"");
Cursor c = db.rawQuery(q, null);
Upvotes: 0
Reputation: 11047
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.
Upvotes: 20
Reputation: 15635
You have to append the %
to the selectionArgs itself:
selectionArgs = new String[] { searchString + "%" };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);
Note: Accordingly %
and _
in the searchString
string still work as wildcards!
Upvotes: 24