|
postgresql里有很多好用的数据类型和扩展类型,例如ltree,例如period,但在通过jdbc访问pg时,使用这些特别的数据类型往往会遇到一些小麻烦。
以自身遇到的问题为例,在使用PreparedStatement构造sql时,period类型的字段可以通过下面的方法使用:
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBConnection.getConnection();
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO test_table (valid_periods) ");
sb.append("VALUES ( period(?, ?) )");
pstmt = conn.prepareStatement(sb.toString());
pstmt.setTimestamp(1, timestamp1);
pstmt.setTimestamp(2, timestamp2);
pstmt.executeUpdate();
} catch (Exception e) {
...
} finally {
...
}
【WARNING】下面的方法之后测试失败,setObject仅在值为null时不报错,非null时仍然失败。
ltree类型可以通过setObject来设置值,使用setString报错。
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBConnection.getConnection();
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO test_table (cities_ltree) ");
sb.append("VALUES ( ? )");
pstmt = conn.prepareStatement(sb.toString());
pstmt.setObejct(1, "北京.上海.东京");
pstmt.executeUpdate();
} catch (Exception e) {
...
} finally {
...
} |
|
|