Inserting into custom SQL types with prepared statements in java

后端 未结 2 923
挽巷
挽巷 2020-12-29 06:40

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\         


        
相关标签:
2条回答
  • 2020-12-29 06:46

    Another approach would have been

    st.setObject(1, 'spades', Types.OTHER);
    
    0 讨论(0)
  • 2020-12-29 06:53

    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, ?);
    
    0 讨论(0)
提交回复
热议问题