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?
Working with JDBC IN array parameter is hard. It is more harder if you want your query works across all DBMS. That was why I created JDBC utilities to work with JDBC IN array parameters easier.
1. If Maven, add the below dependency into your pom.xml
<dependency>
<groupId>com.appslandia</groupId>
<artifactId>appslandia-common</artifactId>
<version>6.8</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} );
// OR stat.setIntArray("example_array", 1, 2, 3);
ResultSet rs = stat.executeQuery();
while (rs.next()) {
// DO THINGS
}
rs.close(); stat.close();
4. Non IN array 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.setString("str_b", not_null_string_value);
stat.setString2("str_b", null_or_string_value);
// setLong, setFloat, setDouble, setDate, ...
5. Some Notes
- Parameter name supported. No more ? in your query
- Parameter in Sql need to start with @ (Like Ado.NET)
- IN Array parameter in Sql must be in this syntax IN (@param_name)