Search code examples
javaandroidsqlitewhere-in

Java - SQLite - How to use the set of values for one column in where clause?


I want create query like this:

SELECT * FROM my_table WHERE column_1 in (1, 2, 3);

This query works in SQLite editor but I want to use it in Java. I try to use it like this:

String query = "SELECT * FROM mu_table WHERE coumn_1 in ?";
String[] args = {"(1, 2, 3)"};
Cursor c = db.rawQuery(query, args);

But this doesn't work. The following error occurs:

near "?": syntax error (code 1): , while compiling: SELECT * FROM my_table WHERE column_1 in ?

Why is it incorrect and what is correct way?


Solution

  • String query = "SELECT * FROM mu_table WHERE coumn_1 in (?, ?, ?)";
    String[] args = new String[]{String.valueOf(1), String.valueOf(2), String.valueOf(3)};
    Cursor c = db.rawQuery(query, args);
    

    As it is required to pass selection argument compulsorily as string we can pass either as

    String[]{String.valueOf(1), String.valueOf(2), String.valueOf(3)}
    

    or as

    String[]{"1", "2", "3"}
    

    but it will compare as number only and not String. To make it compared as string we have to pass as

    String[]{'1','2','3'}
    

    but it is not required in current question context.