Using Java arrays to insert, retrieve, & update PostgreSQL arrays
来源:互联网 发布:耳骨夹淘宝 编辑:程序博客网 时间:2024/06/05 04:32
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 YorkChicagoSan Francisco
Country: Canada---------------MontrealTorontoVancouver
Country: UK---------------LondonBirminghamOxford
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)
- Using Java arrays to insert, retrieve, & update PostgreSQL arrays
- Perl using Arrays
- java Arrays
- Arrays.java
- 【Java】Arrays
- Java-Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- Arrays
- 网络通信框架Retrofit2
- 基于java的中文分词工具ANSJ
- jq动态修改select 的option值,使option值自动选中
- 探究 Java 虚拟机栈
- android,harmony,java的未来
- Using Java arrays to insert, retrieve, & update PostgreSQL arrays
- nyoj 518 取球游戏
- VR/AR技术杂选
- python 使用set对列表去重,并保持列表原来顺序
- Vue 开发教程之一 环境配置
- apk签名机制
- 【bzoj 1176】Mokia(CDQ分治)
- python 遍历 程序 动态库依赖 ,减少不必要依赖,减少启动时间
- 初识Avro