1

I am looking for verification on the following:

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

I have 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.

Community
  • 1
  • 1
user6401178
  • 183
  • 2
  • 11
  • What is the question? – antoniodvr Jul 12 '16 at 18:07
  • @4castle it wouldn't have been hard to make this feature avail in jdbc. maybe the future versions will do. – user6401178 Jul 12 '16 at 18:13
  • @4castle this constitutes an ans by me. write it and i'll accept. – user6401178 Jul 12 '16 at 18:20
  • @user6401178 I was thinking that... I wasn't totally sure though what your question was or what the appropriate answer would be. I've moved my comments to the answer. – 4castle Jul 12 '16 at 18:22
  • The answer already stated how it is to be solved, therefor I have closed is as a duplicate. I also suggest you to use full words (question instead of Q, answer instead of ans, available instead avail), it makes communication a lot clearer then random textspeak abbreviations. – Mark Rotteveel Jul 12 '16 at 19:00
  • Please don't roll back genuine improvements to your question. – Martijn Pieters Jul 14 '16 at 09:42
  • @MartijnPieters pls dont remove my genuine comments and dont bully my Qs. my Qs have other purposes than adding points to your pal's account. – user6401178 Jul 14 '16 at 14:31
  • @user6401178: you may have misunderstood the purpose of this site, and no-one is getting points from the edits. I've locked the post; editors here improve posts for *future visitors* that may want to check if they have the same problem. – Martijn Pieters Jul 14 '16 at 16:09
  • @user6401178: also, please adhere to our [behaviour guidelines](https://stackoverflow.com/help/be-nice). No one is 'bullying' you here. If you disagree with these policies or the edits made to your post, feel free to use the 'contact us' link in the footer of every page or ask a question on [Meta]. – Martijn Pieters Jul 14 '16 at 16:11

1 Answers1

4

You won't be able to use a PreparedStatement 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.

4castle
  • 32,613
  • 11
  • 69
  • 106