gpt4 book ai didi

postgresql - 在 JDBC 中将数组传递给 postgres

转载 作者:行者123 更新时间:2023-11-29 12:15:32 24 4
gpt4 key购买 nike

我想使用 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"

最佳答案

你可以像这样使用 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
}

关于postgresql - 在 JDBC 中将数组传递给 postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56525121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com