我有一些自定义类型。它们基本上都是枚举。以下是它们的示例:
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.
他们很高兴给我一个提示,但我不确定如何遵循它。
答案 0 :(得分:22)
您是否尝试将列投射到枚举?
// Setup stuff up here.
sql = "INSERT INTO foo (suit) VALUES (?::card_suit)";
st.setString(1, 'spades');
st.executeUpdate(sql);
在“网络编码博客”的Convert between Java enums and PostgreSQL enums文章中解释了样本:
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, ?);
答案 1 :(得分:0)
应该是另一种方法
st.setObject(1, 'spades', Types.OTHER);