首页 > 解决方案 > 在 Java 和 PostgreSQL 中使用 createArrayOf 时,ResultSet 为空

问题描述

我正在尝试使用 s 数组查询产品id表。这是该方法的一个片段:

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

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

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

statement.setArray(1, array);

ResultSet results = statement.executeQuery();

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

return products;

product包含 3 行,ids 为 1、2 和 3。products返回 null。知道为什么吗?

谢谢

编辑

根据第 9.23.1 节

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

例子(1,2,3)

所以,我认为问题变成了:如何从 my 获取标量表达式列表ArrayList

标签: javaarrayspostgresqlprepared-statementsqlconnection

解决方案


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

SELECT * FROM product WHERE id = ANY(?)

推荐阅读