This question already has an answer here:

I want to select all records form database using WHERE IN, using values form an array that I have. Is there a way to actually pass the array to the query? I tried SELECT id FROM tag WHERE name IN "+myArray.toString()+". But, of course, it is destined to fail) I could use preparedStatement, but number of values is always different and quite large - 5000 or so. Or maybe I should take a different approach?

share|improve this question

marked as duplicate by Colonel Thirty Two, Paul Roub, Sean O'Toole, EdChum, karthik Aug 1 '15 at 8:09

This question was marked as an exact duplicate of an existing question.

2  
You should always use prepared statements instead of string concatenation for SQL creation. Give MyBatis or Hibernate a look if you want a little more flexibility on what you can use as an input. – bakoyaro Jul 31 '15 at 14:33
    
But, I heard that preparedStatement is much slower then string concat. Is it true? (Though, I know preparedStatement is good against sql injections) – Sermilion Jul 31 '15 at 21:33

If you don't want to use normal concatenation to do this just use a StringBuilder, which is MUCH more efficient since it only actually creates the string when you use the toString() method.

private String ArrayToString(String[] array)
{
    StringBuilder buffer = new StringBuilder();
    buffer.append(array[0]);

    for (int i = 1; i < array.length; i++)
    {
        buffer.append(",");
        buffer.append(array[i]);
    }

    return buffer.toString();
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.