gpt4 book ai didi

java - 子句和 setArray() 中的 Postgres SQL

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:02:25 26 4
gpt4 key购买 nike

我正在使用 Java 1.7、JDBC 4 和 Postgres。我正在尝试使用带有数组的 PreparedStatement 来填充 SQL in 子句。但是,生成的 SQL 中似乎有“{”和“}”。这是代码:

PreparedStatement ptmt = 
connection.prepareStatement("select * from foo where id in (?)");
String[] values = new String[3];
values[0] = "a";
values[1] = "b";
values[2] = "c";
ptmt.setArray(1, connection.createArrayOf("text", values));

生成的 SQL 如下所示:

select * from foo where id in ('{"a","b","c"}')

哪个,行不通。它应该是这样的:

select * from foo where id in ("a","b","c")

select * from foo where id in ('a','b','c')

我在这里错过了什么?

最佳答案

使用= ANY子查询表达式。

PreparedStatement ptmt = connection.prepareStatement("select * from foo where id = ANY(?)");
String[] values = new String[]{"a","b","c"};
ptmt.setArray(1, connection.createArrayOf("text", values));

如果您需要在查询中强制执行类型,您可以这样做。

select * from foo where id = ANY(?::text[])

PostgreSQL documentation有更多细节。这个片段值得注意:

SOME is a synonym for ANY. IN is equivalent to = ANY.

关于java - 子句和 setArray() 中的 Postgres SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16661545/

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