PreparedStatement with list of parameters in a IN clause [duplicate] PreparedStatement with list of parameters in a IN clause [duplicate] java java

PreparedStatement with list of parameters in a IN clause [duplicate]


What I do is to add a "?" for each possible value.

var stmt = String.format("select * from test where field in (%s)",                         values.stream()                         .map(v -> "?")                         .collect(Collectors.joining(", ")));

Alternative using StringBuilder (which was the original answer 10+ years ago)

List values = ... StringBuilder builder = new StringBuilder();for( int i = 0 ; i < values.size(); i++ ) {    builder.append("?,");}String placeHolders =  builder.deleteCharAt( builder.length() -1 ).toString();String stmt = "select * from test where field in ("+ placeHolders + ")";PreparedStatement pstmt = ... 

And then happily set the params

int index = 1;for( Object o : values ) {   pstmt.setObject(  index++, o ); // or whatever it applies }      


You could use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Code:

PreparedStatement statement = connection.prepareStatement("Select * from test where field in (?)");Array array = statement.getConnection().createArrayOf("VARCHAR", new Object[]{"A1", "B2","C3"});statement.setArray(1, array);ResultSet rs = statement.executeQuery();


You can't replace ? in your query with an arbitrary number of values. Each ? is a placeholder for a single value only. To support an arbitrary number of values, you'll have to dynamically build a string containing ?, ?, ?, ... , ? with the number of question marks being the same as the number of values you want in your in clause.