使用java中的预准备语句插入自定义SQL类型 [英] Inserting into custom SQL types with prepared statements in java
本文介绍了使用java中的预准备语句插入自定义SQL类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些自定义类型。它们基本上都是枚举。以下是它们的示例:
I have some custom types. They are all basically enums. Here is an example of what they look like:
CREATE TYPE card_suit AS ENUM
('spades',
'clubs',
'hearts',
'diamonds');
我在Java中有一些准备好的语句,看起来像这样:
And I have some prepared statements in Java, which look something like this:
// Setup stuff up here.
sql = "INSERT INTO foo (suit) VALUES (?)";
st.setString(1, 'spades');
st.executeUpdate(sql);
Java给了我一些令人讨厌的例外:
And Java gives me some nasty exceptions like this:
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.
他们很高兴给我一个提示,但我不确定如何遵循它。
It's nice of them to give me a hint, but I'm not sure exactly how to follow it.
推荐答案
您是否尝试将列转换为枚举?
Have you tried to cast column to enum?
// Setup stuff up here.
sql = "INSERT INTO foo (suit) VALUES (?::card_suit)";
st.setString(1, 'spades');
st.executeUpdate(sql);
在Java enums和PostgreSQL枚举之间转换A web coding blog的文章,包含样本:
Explained in Convert between Java enums and PostgreSQL enums article of 'A web coding blog' with samples:
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, ?);
这篇关于使用java中的预准备语句插入自定义SQL类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文