java - 在 pgadmin 中运行良好,但在 java 代码中不起作用
问题描述
with recursive
Ancestor(a,d) as (select parent as a, child as d from ParentOf
union
select Ancestor.a , ParentOf.child as d
from Ancestor, ParentOf
where Ancestor.d = ParentOf.parent)
嗨,我在 pgadmin 中运行了上面的代码,它运行良好,所以我尝试以同样的方式将它移到我的 java 代码中。但这里称为 SQL 语法错误。这是什么原因?我也放了;在 SQL 语句中,但发生了同样的错误。
stmt.executeUpdate("with recursive " +
"Ancestor(a,d) as (select parent as a, child as d from ParentOf " +
"union " +
"select Ancestor.a , ParentOf.child as d " +
"from Ancestor, ParentOf " +
"where Ancestor.d = ParentOf.parent)");
下面是错误
Exception in thread "main" org.postgresql.util.PSQLException: error: syntax error, at the end of input
Position: 185
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:473)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:393)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:322)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:308)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:284)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:258)
at SqlTest3.main(SqlTest3.java:44)
解决方案
你有两个错误。首先,要运行查询,您需要使用executeQuery()
. 其次,Java 中的 SQL 字符串不包含最终SELECT
语句,它只包含 CTE。
ResultSet rs = stmt.executeQuery(
"with recursive "Ancestor(a,d) as (" +
"select parent as a, child as d from ParentOf " +
"union " +
"select Ancestor.a ParentOf.child as d " +
"from Ancestor " +
" join ParentOf on Ancestor.d = ParentOf.parent " +
") " +
"select * from ancestor"); // <<< this SELECT was missing
我还用“现代”(超过 25 年)显式 JOIN 运算符替换了 where 子句中古老而过时的隐式连接,这是目前推荐的编写连接的方法。
推荐阅读
- leaflet - 使用带有传单的草皮
- javascript - 如何使用 JavaScript 和 createElement 添加带有事件的 HTML 元素?
- javascript - 不使用 react-router-dom 渲染
- javascript - 验证对象解构
- javascript - 如何在 JS Intl API 中获取语言中立的语言环境
- java - 将 JsonIgnore 用于其他类中的属性
- django - 如何将静态文件分配给初始 forms.FileField?
- java - 在 Apache Camel xml 验证中使用 xsi:schemaLocation 属性
- python - 如果满足条件,则提取上下行
- html - React Table 缩放复选框对齐