Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java PreparedStatement set IN parameter as int array [duplicate]

Possible Duplicate:
PreparedStatement IN clause alternatives?

SELECT * FROM tableName WHERE id IN ?

I wish to set the PreparedStatement's IN parameter as an int[]. For example, an integer array of {1, 2, 3, 4} would become IN (1,2,3,4) in the query.

Is there a simple way to achieve this functionality using PreparedStatement's methods, or must I dynamically create the IN parameter as a string by looping over the array?

I imagine something similar to #setString(int parameterIndex, String x) but of course for an int array.

like image 965
FThompson Avatar asked Mar 16 '26 03:03

FThompson


1 Answers

I'd recommend Spring JDBC. See how easy to start working with it:

    NamedParameterJdbcTemplate t = new NamedParameterJdbcTemplate(dataSource);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("ids", Arrays.asList(1, 2));
    List<Map<String, Object>> list = t.queryForList("select * from t1 where id in (:ids)", params);

You will see that it's not only IN what's good about Spring JDBC. Named parameters, no need to create / close Connection, PreparedStatement, ResultSet, no checked exceptions, declarative transaction support and many other things.

like image 55
Evgeniy Dorofeev Avatar answered Mar 18 '26 17:03

Evgeniy Dorofeev



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!