Reputation: 417
I wrote this rawQuery that gives me an empty cursor:
String query = "SELECT * FROM " + TBL_NAME + " WHERE ? = ?";
String[] args = new String[] {COL_NAME, Long.toString(id)};
Cursor c = db.rawQuery(query, args);
But if I do the following query I get the expected results:
String query = "SELECT * FROM " + TBL_NAME + " WHERE " + COL_NAME + " = " + Long.toString(id);
Cursor c = db.rawQuery(query, null);
I gathered that I can't use table name as one of the arguments of a 'rawQuery' method. But i'm not sure why not (I presume that it surrounds the argument with ' ', but it's only a guess).
Other than that I came to the conclussion that the args should be only used in order to include user inputs to the query, and in that regards looks like its just better to use a SQLiteStatement
.
In summary: Where (and if possible why) shoul I use args in a rawQuery (instead of just concatenated in the string). And why should I use a rawQuery at all instead a SQLiteStatement (or simply query)?
Upvotes: 0
Views: 508
Reputation: 17105
As far as I know the COL_NAME can't be replaced with "?". Android only takes "?" as "arguments", not as "selection"
final String query = "SELECT * FROM " + TBL_NAME + " WHERE COL_NAME=?";
final String[] args = new String[] {Long.toString(id)};
final Cursor c = db.rawQuery(query, args);
Or better use this method
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
In your case it would be like this:
final String[] args = new String[] {Long.toString(id)};
final Cursor c = db.query(TBL_NAME, null, COL_NAME + "=?", args, null, null, null);
Upvotes: 1