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?

1

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 )
What do you suggest if you have to wrap the values in quotations?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.