4

i'm trying to append some integer values to my database, i have made this prepared statement

 stmt = connection.prepareStatement("UPDATE domotica.artefatti SET id_sensori = array_append(id_sensori,?) WHERE id=?");

I have an integers array like this one:

int [] integerarray = {values...};

I would like to convert/cast it so that I can do something like this:

stmt.setArray(1,correctarray);

1 Answer 1

5

You need to create a JDBC Array instance through the connection. But that only accepts an Object[] so you need to convert your int[] array to that:

int[] intlist = {....};
Object[] values = Arrays.stream(intlist).mapToObj(i -> Integer.valueOf(i)).toArray();
Array array = con.createArrayOf("int", values);
pstmt.setArray(1, array);

Note that array_append() can't be used to append one array to another. You need to use array_cat() instead if you pass an array to the PreparedStatement.

Sign up to request clarification or add additional context in comments.

2 Comments

This is mostly true. While JDBC does specify the array must be of objects, the PgJDBC driver does support primitive int arrays. See github.com/pgjdbc/pgjdbc/blob/master/pgjdbc/src/main/java/org/…
@coladict: but Connection.createArrayOf() only accepts Object[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.