19

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
  • 1
    If you have control of the schema, a check constraint on a text column can work the same as the enum, yet is easier to work with in Java. Commented Feb 26, 2016 at 21:13

2 Answers 2

27

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, ?);
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I needed. Haven't used casting in SQL before. Thanks!
0

Another approach would have been

st.setObject(1, 'spades', Types.OTHER);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.