postgresql - 将数组传递给 JDBC 中的 postgres
问题描述
我想使用 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
}
推荐阅读
- google-analytics - AMP 分析表 - 提交跟踪
- python - 如何计算python中的平均时间差?
- c# - 使用 Cinchoo ETL 修改 CSV 文件标题/列名
- php - 在设备中打开并使用 api 时出现 IONIC 3 CORS 问题
- java - 阿帕奇点燃。如何创建计时器任务(基于cron)而不在每个节点上执行?
- ios - 添加到 UIButton 扩展的初始化函数
- amazon-web-services - Amazon Connect - 出站号码检查联系流 - Lambda 函数
- jenkins - 将工件文件和文件夹移动到一个(发布)文件夹
- javascript - 箭头函数是否必须始终返回一个值?
- selenium-webdriver - 报告生成器说 Cucumber 不是有效的报告