我正在尝试使用 Postgres 9.1 的 prepared statements使用 Postgres 的官方 JDBC 驱动程序 9.3-1100 的 Scala 应用程序的功能。
如果我这样做,一切都会正常,并且我会得到“foo”:
conn.prepareStatement("PREPARE prep(text) AS SELECT $1").executeUpdate();
val cmd = conn.prepareStatement("EXECUTE prep('foo')");
但是,如果我尝试参数化它:
conn.prepareStatement("PREPARE prep(text) AS SELECT $1").executeUpdate();
val cmd = conn.prepareStatement("EXECUTE prep(?)");
cmd.setString(1, "foo");
然后我在执行命令时收到此错误:
org.postgresql.util.PSQLException: ERROR: there is no parameter $1
Position: 14
org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2161)
org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1890)
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:560)
org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:417)
org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:410)
com.jolbox.bonecp.PreparedStatementHandle.execute(PreparedStatementHandle.java:140)
我已经尝试了多种不同的方法,但找不到任何方法来成功参数化此查询。
我已经使用 Npgsql 驱动程序从 .net 应用程序中完成了类似的操作,并且它有效,所以我无法弄清楚为什么 JDBC 驱动程序不允许我这样做。这只是 JDBC 驱动程序的限制吗?有什么解决办法吗?
最佳答案
当您使用 JDBC 准备语句时,您需要准备实际的语句。您当前正在尝试准备并执行 PostgreSQL 特定的 PREPARE
和 EXECUTE
命令(这可能是驱动程序内部使用的命令)。
您需要这样做:
val cmd = conn.prepareStatement("SELECT ?");
cmd.setString(1, "foo");
虽然我不确定这是否有效,因为 PostgreSQL 无法决定这里的参数类型。
关于java - 使用 JDBC 中的 Postgres 准备好的语句失败,错误代码为 "there is no parameter $1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21727925/