Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite in operator in query()

Tags:

android

sqlite

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')"}
like image 874
PeterMmm Avatar asked Apr 30 '13 08:04

PeterMmm


People also ask

What does in do in SQLite?

In SQLite, the INSERT INTO statement is used to add new rows of data into a table. After you create the table, this command is used to insert records into the table. You can view the output by using the SELECT statement.

How do I SELECT a specific row in SQLite?

Typically to get a specific row you can always request them by rowid , e.g. SELECT name FROM UnknownTable WHERE rowid = 1; However, there are some atypical situations that preclude this. You'll really want to read up on rowids to ensure that your table is going to behave as you want.

Which operator is negation of in operator in SQLite?

The NOT operator reverses the meaning of the logical operator with which it is used. Eg. NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is negate operator.


2 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);  
like image 106
Hoan Nguyen Avatar answered Sep 20 '22 17:09

Hoan Nguyen


While working on a project and struggling with this very same question I found these other questions (and answers) helpful:

  1. Sqlite Query for multiple values in one columm
  2. Android/SQLite IN clause and placeholders

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.

like image 43
Ryan Manes Avatar answered Sep 18 '22 17:09

Ryan Manes