前言
JDBC訪問Postgresql的jsonb類型字段當然可以使用Postgresql jdbc驅動中提供的PGobject,但是這樣在需要兼容多種數據庫的系統開發中顯得不那么通用,需要特殊處理。本文介紹一種更通用的方式。
JDBC URL中添加參數
在Postgresql的jdbc url中可以添加一個參數,如下:
jdbc:postgresql://xxx.xxx.xxx:5432/postgres?stringtype=unspecified
官方對stringtype參數的解釋是:
stringtype : String
Specify the type to use when binding PreparedStatement parameters set via setString(). If stringtype is set to VARCHAR (the default), such parameters will be sent to the server as varchar parameters. If stringtype is set to unspecified, parameters will be sent to the server as untyped values, and the server will attempt to infer an Appropriate type. This is useful if you have an existing application that uses setString() to set parameters that are actually some other type, such as integers, and you are unable to change the application to use an appropriate method such as setInt().
因此當stringtype=unspecified 時,statement.setString()方法的參數將以未知的類型發送給pg數據庫,由數據庫根據表中字段的類型進行推定和自動轉換。也就是說我們可以以字符串形式給postgresql數據庫中各種類型的數據進行賦值,當然也可以支持jsonb類型。
JDBC代碼示例
建測試表:
create table t_test( name varchar(20) primary key, props jsonb);
插入數據:
Class.forName("org.postgresql.Driver");
Connection con = null;
try {
String url="jdbc:postgresql://xxxx.xxxx.xxxx:5432/postgres?stringtype=unspecified";
con = DriverManager.getConnection(url, "username", "password");
con.setAutoCommit(false);
String sql= "insert into t_test(name, props) values(?,?)";
PreparedStatement statement = con.prepareStatement();
statement.setString(1, "zhangsan");
statement.setString(2, "{"age":23, "email":"zhangsan@xxx.com"}");
statement.executeUpdate();
con.commit();
} catch (Exception ex) {
ex.printStackTrace();
con.rollback();
} finally {
if (con != null) {
con.close();
}
}