user6401178 user6401178 - 3 months ago 5x
Java Question

PreparedStatement with variable number of params yet without iterating on them

Looking for verification on the following:

The way to use PreparedStatement with an unknown number of parameters is the way shown in this Q, and there's no way to get around such iteration on the Java/application side.

I've been looking for a "varargs" kind of method&syntax to feed into the PreparedStatement the variable number of arguments, say on a collection, and plug this as a single variable-placeholder into the query.




This is not a question. looking for verification just not to miss out.


You won't be able to use a PreparedStatement if you if you want to have varying parameters. The SQL string has to have the correct number of question marks. That's why the workaround is to iterate and add the question marks first, and then create the PreparedStatement from that dynamic string.

Part of the motivation for using a PreparedStatement is to avoid SQL injection. The PreparedStatement is like a contract with the database that there will only be this many parameters with this SQL statement. If the parameters could change, it would break that contract and the database would no longer know what to prepare for.