使用Java在PostgreSQL中使用createArrayOf时结果集为空。

huangapple go评论83阅读模式
英文:

ResultSet empty when using createArrayOf in Java with PostgreSQL

问题

我正在尝试使用一个 id 数组来查询 product 表。以下是该方法的片段:

PreparedStatement statement = connection
    .prepareStatement("SELECT * FROM product WHERE id IN (?)");

System.out.println(ids /*ArrayList<Integer>*/); //打印 [3]

Array array = connection.createArrayOf("INTEGER", ids.toArray());
// Array array = connection.createArrayOf("INTEGER", new Integer[]{1, 2, 3}); //<-----也尝试过这个

statement.setArray(1, array);

ResultSet results = statement.executeQuery();

while (results.next()) {
    System.out.println("不会打印这个");
    Product product = new Product(0);
    product.setId(results.getInt("id"));
    products.add(product);
}

return products;

product 包含具有 id 1、2 和 3 的 3 行。products 返回为 null。有任何想法为什么会这样吗?

编辑

根据 9.23.1 节

> 右侧是标量表达式的括号列表

例如 (1,2,3)

所以,我想问题变成了:如何从我的 ArrayList 中获取这个标量表达式列表?

英文:

I'm trying to query product table using an array of ids. Here's a fragment of the method:

PreparedStatement statement = connection
    .prepareStatement(&quot;SELECT * FROM product WHERE id IN (?)&quot;);

System.out.println(ids /*ArrayList&lt;Integer&gt;*/); //prints [3]

Array array = connection.createArrayOf(&quot;INTEGER&quot;, ids.toArray());
// Array array = connection.createArrayOf(&quot;INTEGER&quot;, new Integer[]{1, 2, 3}); //&lt;-----tried this too

statement.setArray(1, array);

ResultSet results = statement.executeQuery();

while (results.next()) {
    System.out.println(&quot;does not print this&quot;);
    Product product = new Product(0);
    product.setId(results.getInt(&quot;id&quot;));
    products.add(product);
}

return products;

Table product contains 3 rows with ids 1, 2 and 3. products returns null. Any idea why?

Thanks

EDIT

According to section 9.23.1

> The right-hand side is a parenthesized list of scalar expressions

example (1,2,3)

So, I think question turns into: how to get that list of scalar expressions from my ArrayList?

答案1

得分: 1

在查询的WHERE子句中检查一个元素是否在数组中,您可以使用ANY。在您的情况下:

SELECT * FROM product WHERE id = ANY(?)

英文:

To check in the WHERE clause of a query, whether an element is in an array you can use ANY. In your case:

SELECT * FROM product WHERE id = ANY(?)

huangapple
  • 本文由 发表于 2020年9月8日 08:19:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63785624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定