27

I want to execute a sqlite query:

select * from table_name where id in (23,343,33,55,43);

The values in the in clause need to be taken from an array of strings:

String values[] = {"23","343","33","55","43"}

How can I achieve that?

Alex
  • 6,849
  • 6
  • 19
  • 36
SuperFrog
  • 7,631
  • 9
  • 51
  • 81
  • Does this answer your question? [Node.js sqlite3 IN operator](https://stackoverflow.com/questions/34349199/node-js-sqlite3-in-operator) – Strider Nov 05 '19 at 00:36

1 Answers1

45

I believe a simple toString() will mostly do the trick:

String values[] = {"23","343","33","55","43"};
String inClause = values.toString();

//at this point inClause will look like "[23,343,33,55,43]"
//replace the brackets with parentheses
inClause = inClause.replace("[","(");
inClause = inClause.replace("]",")");

//now inClause will look like  "(23,343,33,55,43)" so use it to construct your SELECT
String select = "select * from table_name where id in " + inClause;
Sam Dozor
  • 40,335
  • 6
  • 42
  • 42
  • 2
    If some of your values come from user input you are open to possible SQL injection attacks or at least crashes. You should look at the `DatabaseUtils.html#sqlEscapeString(java.lang.String)` and related functions before putting user input into sql statements. – satur9nine Jan 30 '14 at 18:39
  • 1
    You should be sure that none of your values contain [ or ] before doing this replace. A better way would be to take the substring between the first and last characters and wrapping that in ( and ) – SDJMcHattie Nov 27 '14 at 11:09
  • What do you suggest if you have to wrap the values in quotations? – Joshua Pinter Dec 10 '17 at 00:13