Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting into custom SQL types with prepared statements in java

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.

like image 966
Tom Carrick Avatar asked May 13 '12 12:05

Tom Carrick


People also ask

Can we use PreparedStatement for SELECT query in Java?

To retrieve data from a table using a SELECT statement with parameter markers, you use the PreparedStatement. executeQuery method.

What is PreparedStatement in SQL Java?

A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of Statement. Prepared Statement objects have some useful additional features than Statement objects. Instead of hard coding queries, PreparedStatement object provides a feature to execute a parameterized query.

How do you pass parameters in PreparedStatement?

To execute a statement with Where clause using PreparedStatement. Prepare the query by replacing the value in the clause with place holder “?” and, pass this query as a parameter to the prepareStatement() method.

Is PreparedStatement suitable for dynamic SQL?

Prepared statements are interesting from a stored programming perspective because they allow us to create dynamic SQL calls. The SQL text may contain placeholders for data values that must be supplied when the SQL is executed.


1 Answers

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, ?);
like image 183
dani herrera Avatar answered Nov 13 '22 11:11

dani herrera