Reputation: 711
I want to put an array of integers in my jdbc query with H2 database.
Integer[] list = new Integer[]{1,2,3};
String query = "SELECT EXAMPLE FROM DATA WHERE EXAMPLE IN (?)";
PreparedStatement ps = GestionBDD.getConexionBD().prepareStatement(query);
Array array = GestionBDD.getConexionBD().createArrayOf("int", list);
ps.setArray(1, array);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// DO THINGS
}
But doest not work, I am getting this exception : org.h2.jdbc.JdbcSQLException: Data conversion error converting "(1,2,3)"; SQL statement:
I am using H2 database. Can you help me please?
Upvotes: 1
Views: 1057
Reputation: 9655
Using my JDBC utilities to work with JDBC IN array parameters easily:
1. If Maven, add the below dependency into your pom.xml
<dependency>
<groupId>com.appslandia</groupId>
<artifactId>appslandia-common</artifactId>
<version>7.9</version>
</dependency>
2. If no maven, download this jar file
3. Fix your code ( Works all DBMS guaranteed )
static final Sql EXAMPLE_SQL
= new Sql("SELECT EXAMPLE FROM DATA WHERE EXAMPLE IN :example_array");
StatementImpl stat = new StatementImpl(GestionBDD.getConexionBD(), EXAMPLE_SQL);
stat.setIntArray("example_array", new int[] {1, 2, 3} );
ResultSet rs = stat.executeQuery();
while (rs.next()) {
// DO THINGS
}
rs.close(); stat.close();
4. Named parameters / Null parameters
final Sql sampleSql
= new Sql("SELECT * FROM Table WHERE a=:int_a AND b=:str_b)
StatementImpl stat = new StatementImpl(conn, sampleSql);
stat.setInt("int_a", int_value);
stat.setInt2("int_a", null_value);
stat.setString("str_b", str_value);
// ...
5. Some Notes
Upvotes: 1