我try 将值添加到Postgres枚举类型中,如下所示(删除值的循环):
PreparedStatement stmt = conn.prepareStatement("ALTER TYPE my_enum_type ADD VALUE ?;");
stmt.setString(1, "value");
stmt.addBatch();
stmt.executeBatch()
当我运行它时,我得到:
Batch entry 0 ALTER TYPE my_enum_type ADD VALUE 'value' was aborted: ERROR: syntax error at or near "$1"
个
我在谷歌上发现,这可能与选角有关.我将查询更改为:
ALTER TYPE my_enum_type ADD VALUE ?::my_enum_type
个
它会给出相同的错误.
和
ALTER TYPE my_enum_type ADD VALUE cast(? as my_enum_type)
个
在cast
上出现语法错误而失败
I worked around it by concatenating a string with the enum value 和 executing that, but there has to be a better way.
我是Postgres的新手,有什么简单的方法可以解决这个问题吗?
EDIT: In response to comments 和 to avoid confusion:
- How do I make Java & Postgres enums work together for update? is about executing updates 和 not ALTER. The solution there is to cast to the target type, which I tried 和 did not work.
解决方案:
在Laurenz Albe的 comments 之后,我最终将我的解决方案修改为:
try (Statement stmt = conn.createStatement()) {
PGConnection pgconn = conn.unwrap(PGConnection.class);
for (String i : missingValues) {
stmt.addBatch("ALTER TYPE my_enum_type ADD VALUE '" + pgconn.escapeLiteral(i) + "'");
}
stmt.executeBatch();
}