Search code examples
javaarrayspostgresqlpostgresql-9.3

how to convert java.sql.Array to an integer array


Hello to everyone i'm stucked with this simple problem.

i'm trying to load an integer array from my Postgres DB.

My Code:

Array a = rs.getArray("my_field");

int[] b = (int[])a.getArray();

The Exception Displayed:

java.lang.ClassCastException: class [Ljava.lang.Integer; cannot be cast to class [I ([Ljava.lang.Integer; and [I are in module java.base of loader 'bootstrap')

How can i convert java.sql.Array into an int[] array or into an arraylist?


Solution

  • You need to cast it to an array of Integer:

    Array a = rs.getArray("my_field");
    Integer[] b = (Integer[])a.getArray();
    

    Note that a will be null if the column is null in the database, so you should check that before calling a.getArray().