Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a list of integers while preparing SQL queries in Java

I have a query like this - select * from tbl where ... and colname in (2,3,4)

When I prepare the query (... ' colname in (?)' ) using a PreparedStatement in Java, what setter method should I call to set these integers ? The integers are available in an int array and the size varies. If it matters, the database is MySQL and the column in question is of int type.

like image 427
Vijay Dev Avatar asked Jan 26 '26 02:01

Vijay Dev


2 Answers

you can use another syntax

WHERE colname = ANY (?)

and call PreparedStatement.setArray(). You have to provide an instance of java.sql.Array as parameter.One advantage of ANY instead of IN is, that you can pass an empty array without causing a SQL syntax error.

like image 179
Learning Avatar answered Jan 27 '26 17:01

Learning


As an addendum to Learning's explanation:

Creating an Array can be tricky.

There's a creator method in Connection in JDK 1.6 and later. http://download.java.net/jdk7/docs/api/java/sql/Connection.html#createArrayOf(java.lang.String,%20java.lang.Object[])

Since JDK1.6 is the latest stable release, your JDBC drivers may not support it.

You can try and create your own Array implementation, but that may not work with all JDBC connector implementations.

like image 26
Mike Samuel Avatar answered Jan 27 '26 16:01

Mike Samuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!