Inserting into custom SQL types with prepared statements in java

拟墨画扇 提交于 2019-12-03 09:41:21

问题


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');

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);

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.


回答1:


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);

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, ?);


来源:https://stackoverflow.com/questions/10571821/inserting-into-custom-sql-types-with-prepared-statements-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!