我想使用JDBC在Postgres中执行以下查询:
with things as (values(1),(2)) select * from things;
所以我的Java代码如下:
String sql = "with things as (?) select * from things";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setArray(1, conn.createArrayOf("INTEGER", new Integer[]{1, 2});
但这会引发以下错误:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
答案 0 :(得分:1)
您可以使用unnest
来完成所需的操作:
Integer[] id = {1, 2};
Array array = connection.createArrayOf("int4", id);
try (PreparedStatement stmt = connection.prepareStatement(
"with things as (select unnest((?)::integer[])) select * from things")) {
stmt.setArray(1, array);
ResultSet rs = stmt.executeQuery();
// use the result set
}