Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an int [] Array into a java.sql.Array

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 Answers

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.