尝试在PostGres中执行array_append函数时键入强制转换异常

时间:2017-02-02 12:00:59

标签: java arrays postgresql append prepared-statement

函数 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)

以下是表格'测试'

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

有人能让我知道如何解决这个问题吗?但是,如果没有PreparedStatement

,则可以使用此功能

1 个答案:

答案 0 :(得分:2)

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

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