Arrays are a powerful programming feature frequently used by developers, both in Java and in PL/pgSQL. Interfaces can potentially become tricky, however, when the two try and talk to each other. This section explores how you can write simple code that uses the java.sql.Array Interface to insert, retrieve, & update arrays in PostgreSQL.
To illustrate the functionality, let’s set up a simple table that stores country names in one column as TEXT and a list of some of the country’s cities in the second column as a TEXT ARRAY.
CREATE TABLE city_example (
country TEXT,
cities TEXT[]
);
Now we will use the JDBC interface to insert data into this table, retrieve it, and update it.
Inserting ARRAYs
Anyone familiar with Java has used arrays in one form or the other. Before these arrays can be stored in PostgreSQL, however, they need to be mapped to the Interface provided in the java.sql package … Array.
The JDBC driver provides functions that map Java arrays to their corresponding PostgreSQL arrays. Mapping is database-specific and is defined in PostgreSQL JDBC’s org.postgresql.jdbc2.TypeInfoCache file. It is important to note that mapping is case sensitive. As an example, “INTEGER” is not the same as “integer”.
In the code that follows, function createArrayOf of the Connection Interface is used to convert Java String arrays to PostgreSQL TEXT Arrays before insertion.
try {
String[] usa = {"New York", "Chicago", "San Francisco"};
String[] canada = {"Montreal", "Toronto", "Vancouver"};
String[] uk = {"London", "Birmingham", "Oxford"};
/*
Convert String[] to java.sql.Array using JDBC API
*/
Array arrayUSA = conn.createArrayOf("text", usa);
Array arrayCanada = conn.createArrayOf("text", canada);
Array arrayUK = conn.createArrayOf("text", uk);
String sql = "INSERT INTO city_example VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "USA");
pstmt.setArray(2, arrayUSA);
pstmt.executeUpdate();
pstmt.setString(1, "Canada");
pstmt.setArray(2, arrayCanada);
pstmt.executeUpdate();
pstmt.setString(1, "UK");
pstmt.setArray(2, arrayUK);
pstmt.executeUpdate();
conn.commit();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
Please note that the data type specified in Connection.createArrayOf has to be a PostgreSQL type, not java.sql.Types. The JDBC driver looks up the data type at runtime to create the java.sql.Array object.
This code, when executed, results in the following data in the city_example table:
select * from city_example ;
country | cities
---------+--------------------------------------
USA | {"New York",Chicago,"San Francisco"}
Canada | {Montreal,Toronto,Vancouver}
UK | {London,Birmingham,Oxford}
(3 rows)
Retrieving ARRAYs
Process of retrieving arrays is the exact reverse of inserting them. In the example below, first step is to get a ResultSet with the required data and second step is to convert PostgreSQL TEXT Arrays to Java String arrays.
try {
String sql = "SELECT * FROM city_example";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
System.out.println("Country: " + rs.getString(1));
System.out.println("---------------");
Array cities = rs.getArray(2);
String[] str_cities = (String[])cities.getArray();
for (int i=0; i
System.out.println("");
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
For the above code, output to stdout is:
Country: USA
---------------
New York
Chicago
San Francisco
Country: Canada
---------------
Montreal
Toronto
Vancouver
Country: UK
---------------
London
Birmingham
Oxford
Updating ARRAYs
Process of updating arrays in PostgreSQL is pretty close to that of inserting them. In the code below, a new set of USA cities is declared as a Java String array, which is then converted to a PostgreSQL TEXT array before updating the existing row.
try {
String[] usa = {"New York", "Chicago", "San Francisco", "Miami", "Seattle"};
Array arrayUSA = conn.createArrayOf("text", usa);
String sql = "UPDATE city_example SET cities = ? WHERE country = 'USA'";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setArray(1, arrayUSA);
pstmt.executeUpdate();
conn.commit();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
After execution of this code, the database table looks as follows:
select * from city_example ;
country | cities
---------+----------------------------------------------------
Canada | {Montreal,Toronto,Vancouver}
UK | {London,Birmingham,Oxford}
USA | {"New York",Chicago,"San Francisco",Miami,Seattle}
(3 rows)