【问题标题】:Type cast exception while trying to execute array_append function in PostGres尝试在 PostGres 中执行 array_append 函数时键入强制转换异常
【发布时间】:2017-06-19 11:52:55
【问题描述】:

array_append 在 postgres 中将元素附加到数组的函数具有如下签名

Schema   |     Name     | Result data type | Argument data types  |  Type  | Security | Volatility |  Owner   | Language | Source code  |           Description            
------------+--------------+------------------+----------------------+--------+----------+------------+----------+----------+--------------+----------------------------------
 pg_catalog | array_append | anyarray         | anyarray, anyelement | normal | invoker  | immutable  | rdsadmin | internal | array_append | append element onto end of array

当我使用准备好的语句执行它以删除如下所示的数组元素时,

StringBuilder builder = new StringBuilder();
builder.append("update test set tags = array_append(tags, ?) where id = ?")
pstmt = cursor.prepareStatement(builder.toString());
int queryCount = 0;
pstmt.setString(++queryCount, "2181");
pstmt.setString(++queryCount, "123");

我得到以下异常

org.postgresql.util.PSQLException: ERROR: function array_remove(text[], character varying) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 60
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2284)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2003)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:200)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:424)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:161)
        at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:133)

下面是“Test”表的架构

Column     |           Type           |   Modifiers   | Storage  | Stats target | Description 
---------------+--------------------------+---------------+----------+--------------+-------------
 id          | text                     | not null      | extended |              | 
 tags    | text[]                    | not null      | extended |              | 

有人可以告诉我如何解决这个问题吗?但是,在没有 PreparedStatement 的情况下使用此方法

【问题讨论】:

  • 你能告诉我们'array_append'代码吗?
  • Postgres内置的array_append函数不符合你的要求? postgresql.org/docs/9.1/static/functions-array.html
  • @P.Merkle 我猜这是内置函数
  • 此外,仅在与准备好的语句一起使用时才会出现此错误。如果我使用附加参数的字符串 sql 语句执行 UpdateQuery,那么它可以正常工作
  • 你的sql 变量中有什么,或者你的意思是builder.toString()

标签: java arrays postgresql append prepared-statement


【解决方案1】:

尝试将第一个参数转换为架构中定义的text

UPDATE test SET tags = array_append(tags, ?::text) WHERE id = ?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多