我有一些自定义类型。它们基本上都是枚举。这是它们的外观示例:
CREATE TYPE card_suit AS ENUM ('spades', 'clubs', 'hearts', 'diamonds');
而且我有一些用Java准备的语句,看起来像这样:
// Setup stuff up here. sql = "INSERT INTO foo (suit) VALUES (?)"; st.setString(1, 'spades'); st.executeUpdate(sql);
Java给了我一些讨厌的异常,例如:
org.postgresql.util.PSQLException: ERROR: column "suit" is of type card_suit but expression is of type character varying Hint: You will need to rewrite or cast the expression.
他们很高兴给我一个提示,但是我不确定如何遵循它。
您是否尝试过将列强制转换为枚举?
// Setup stuff up here. sql = "INSERT INTO foo (suit) VALUES (?::card_suit)"; st.setString(1, 'spades'); st.executeUpdate(sql);
在“ A Web编码博客”的Java枚举和PostgreSQL枚举之间的转换中进行了解释,并提供了示例:
INSERT INTO pet (pet_id, pet_type, name) VALUES (?, CAST(? AS animal_type), ?); --or INSERT INTO pet (pet_id, pet_type, name) VALUES (?, ?::animal_type, ?);