[英]Works well in pgadmin but doesn't work in java code
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 子句中古老而过时的隐式连接,这是目前推荐的编写连接的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.