Using Java arrays to insert, retrieve, & update PostgreSQL arrays

本文介绍如何使用Java SQL Array接口在PostgreSQL中插入、检索和更新数组数据。通过示例展示具体的Java代码实现,包括创建数组、更新数组元素等操作。

source: https://blog.2ndquadrant.com/using-java-arrays-to-insert-retrieve-update-postgresql-arrays/

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<str_cities.length; i++) {
 System.out.println(str_cities[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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值