Reputation: 24640
I'm calling SQLite like this
String[] args = new String[]{"(A,B)"}
Cursor cur = db.query("tab1", null, "name in ?", args, null, null, null);
and receiving Exception:
android.database.sqlite.SQLiteException: near "?": syntax error: , while compiling: SELECT * FROM tab1 WHERE name in ?
How to use in
operator in query() ?
I already tried
String[] args = new String[]{"('A','B')"}
Upvotes: 7
Views: 6322
Reputation: 146
If i understand right, you can solve your problem like this:
List<String> exercise = new ArrayList<>();
exercise.add(parameter1);
exercise.add(parameter2);
exercise.add(parameter3);
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM exersisesenglish WHERE sex " + "
=?" + " AND level" + "=?" + " AND wish" + "=?" + " AND place" + "=?" + " AND lang" +
"=?" +" AND stay_exersise IN (" + exercise.get(0) + "," + exercise.get(1) + "," +
exercise.get(2) + "," + exercise.get(3) + ")", new String[]{String.valueOf(sex),
String.valueOf(level), String.valueOf(wish), String.valueOf(place),
String.valueOf(loc)});
Upvotes: 0
Reputation: 18151
String[] args = new String[]{A,B} // if A, B are variables
String[] args = new String[]{"A","B"}
Cursor cur = db.query("tab1", null, "name in (?,?)", args, null, null, null);
Upvotes: 5
Reputation: 59
While working on a project and struggling with this very same question I found these other questions (and answers) helpful:
Here is what I've found works:
String[] args = new String[] {"A", "B"};
Cursor cur = db.query("tab1", null, "name in(?,?)", args, null, null, null);
As will:
String args = "A, B";
Cursor cur = db.query("tab1", null, "name in(" + args + ")", null, null, null, null);
So you can either use multiple ?
with the IN()
statement and match each with an element in selectionArgs
array (like the first example). If you have multiple conditions in your WHERE
clause, make sure to match the ?
with the correct element in selectionArgs
:
String[] args = new String[] {"Current", "A", "B"};
Cursor cur = db.query("tab1", null, "IsCurrent=? AND name in(?,?)", args, null, null, null);
Or you can just use a string made up of comma-delineated arguments directly in the IN()
statement in the selection
string itself (like the second example).
The referenced questions seemed to indicate that you could use a single ?
in the IN()
and somehow expand the associated parameter(s), but I was not able to get that to work.
Upvotes: 4
Reputation: 257
If I am not mistaken, arg parsing does not work with IN clause. So you can't use '?' in your WHERE clause.
You should do something like this :
String args = "A, B";
Cursor cur = db.query("tab1", null, "name in (" + args + ")", null, null, null, null);
and construct your args with a loop if needed.
Upvotes: 0