Jdbi: 在 postgres 中转义 jsonb 问号运算符

创建于 2015-09-18  ·  6评论  ·  资料来源: jdbi/jdbi

我正在尝试将 jdbi 与 postgres 和 jsonb 一起使用来编写这样的查询:

select id, data from some_table where data ? :key

不幸的是,jdbi 将这个问号解释为变量的占位符。 如何转义问号以便我可以使用 postgres 问号运算符?

最有用的评论

原来这是 jdbc 中的一个上游问题。 他们已经实施了一种逃避它的方法。 你必须用??。 像这样:

select id, data from some_table where data ?? :key

所有6条评论

你试过反斜杠\?吗?

是的,我想我应该提到这一点。 那是我的第一直觉。 但我仍然收到错误消息。

Exception in thread "main" org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException: org.postgresql.util.PSQLException: No value specified for parameter 2. [statement:"select id, createdDate, data from something where data \? ?", located:"select id, createdDate, data from something where data \? ?", rewritten:"select id, createdDate, data from something where data ? ?", arguments:{ positional:{0:'pattern'}, named:{}, finder:[]}]
    at org.skife.jdbi.v2.SQLStatement.internalExecute(SQLStatement.java:1334)
    at org.skife.jdbi.v2.Query.fold(Query.java:173)
    at org.skife.jdbi.v2.Query.list(Query.java:82)
    at org.skife.jdbi.v2.Query.list(Query.java:75)
    at com.ngc.vault.eventer.Query.hasKey(Query.java:45)
    at com.ngc.vault.eventer.Main.main(Main.java:34)
Caused by: org.postgresql.util.PSQLException: No value specified for parameter 2.
    at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:228)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:163)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:615)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:465)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:458)
    at org.skife.jdbi.v2.SQLStatement.internalExecute(SQLStatement.java:1328)
    ... 5 more

原来这是 jdbc 中的一个上游问题。 他们已经实施了一种逃避它的方法。 你必须用??。 像这样:

select id, data from some_table where data ?? :key

Postgres 查询
SELECT json_data FROM employee where json_data -> 'employee' @> '{"name":"Aman"}'

在 postgres 中运行时,上述查询工作正常。 但是当使用 jdbctemplate 运行时,它会抛出一个错误。

Java代码

String sql="SELECT json_data FROM employee where json_data -> 'employee' @> '{\"name\":\"?\"}'";

List<Map<String, Object>> emp = jdbcTemplate.queryForList(sql,param);

在遇到代码的最后一行时,它会抛出一个错误:-列索引超出范围:1,列数:0。 嵌套异常是 org.postgresql.util.PSQLException。

它不能替代“?” 占位符。

这是根据 JDBC 规范。 ?标记不被识别为字符串文字中的参数。

如果您需要将参数插入到该 JSON 字符串中,请使用串联。 使用 Postgres 连接语法,查询将如下所示:

SELECT json_data
FROM employee
WHERE json_data -> 'employee' @> ('{"name": "' || ? || '"}')

另请注意,这是 Jdbi 项目,而不是 JdbcTemplate。 :)

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

dhardtke picture dhardtke  ·  3评论

anjeyy picture anjeyy  ·  3评论

bakstad picture bakstad  ·  5评论

Romqa picture Romqa  ·  5评论

raderio picture raderio  ·  6评论