SQLite in statement in query ()

I call SQLite like this

String[] args = new String[]{"(A,B)"} Cursor cur = db.query("tab1", null, "name in ?", args, null, null, null); 

and getting Exception:

 android.database.sqlite.SQLiteException: near "?": syntax error: , while compiling: SELECT * FROM tab1 WHERE name in ? 

How to use the in operator in a query ()?

I have already tried

 String[] args = new String[]{"('A','B')"} 
+6
source share
3 answers
 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); 
+3
source

While working on the project and struggling with this very question, I found these other questions (and answers) useful:

Here is what I found:

 String[] args = new String[] {"A", "B"}; Cursor cur = db.query("tab1", null, "name in(?,?)", args, null, null, null); 

How will it be:

 String args = "A, B"; Cursor cur = db.query("tab1", null, "name in(" + args + ")", null, null, null, null); 



So you can use a few ? with the IN() operator and map each to an element in the selectionArgs array (as in the first example). If you have multiple conditions in a WHERE , make sure it matches ? with the correct item 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 simply use a string consisting of arguments separated by commas directly in the IN() statement in the selection string itself (for example, the second example).



Related questions seemed to indicate that you could use one ? in IN() and somehow extend the related parameters, but I could not get this to work.

+4
source

If I'm not mistaken, the parsing argument does not work with the IN clause. So you can not 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 if necessary, create arguments using a loop.

0
source

Source: https://habr.com/ru/post/943944/


All Articles