使用java中的预准备语句插入自定义SQL类型

Tom*_*ick 17 java sql postgresql prepared-statement

我有一些自定义类型.它们基本上都是枚举.以下是它们的示例:

CREATE TYPE card_suit AS ENUM
   ('spades',
    'clubs',
    'hearts',
    'diamonds');
Run Code Online (Sandbox Code Playgroud)

我在Java中有一些准备好的语句,看起来像这样:

// Setup stuff up here.
sql = "INSERT INTO foo (suit) VALUES (?)";
st.setString(1, 'spades');
st.executeUpdate(sql);
Run Code Online (Sandbox Code Playgroud)

而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.
Run Code Online (Sandbox Code Playgroud)

他们很高兴给我一个提示,但我不确定如何遵循它.

dan*_*era 23

你有没有尝试将列转换为枚举?

// Setup stuff up here.
sql = "INSERT INTO foo (suit) VALUES (?::card_suit)";
st.setString(1, 'spades');
st.executeUpdate(sql);
Run Code Online (Sandbox Code Playgroud)

在Java enums和PostgreSQL之间的转换中解释了"A web coding blog"文章的样本:

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, ?);
Run Code Online (Sandbox Code Playgroud)