0

I have a List<Long> matchingLongs = new Arraylist(); that I would like to pass to an SQL statement :

WHERE Id IN (matchingLongs);  

How can I dynamically populate the Longs into the query?

If I would print to console it should look like :

WHERE Id IN (1223, 9834, 3, 924, 88778, 65652165223, 34, 8723738793287);  

Thank you all.

Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142

3 Answers3

1

I think you should iterate matchingLongs, and then add each item to a new string.

1
private String getSqlArrayFromList(final List<Long> matchingLongs) {
    StringBuilder sbuilder = new StringBuilder();
    int index = 0;
    for (Long matchingLong : matchingLongs) {
        if (index == 0) {
            sbuilder.append(matchingLong);
        } else if (index > 0 && index < matchingLongs.size()) {
            sbuilder.append(",").append(matchingLong);
        }
        index++;
    }
    return sbuilder.toString();
}
corroborator
  • 321
  • 2
  • 11
0

How about to change one string.

if (matchingLongs.isEmpty()) {
    return;
}
String str = matchingLongs.toString().replaceAll("[", "(").replaceAll("]", ")");
David
  • 17
  • 3