2016-11-01 22 views
2

acttype是enumcs所以你不能沒有它轉換成一enumcs INSERT INTO dir_act (actcode,actname,acttype,national_code) VALUES (?,?,?::enumcs,?)Java&Postgres枚舉 - 我如何讓它們一起工作來更新?

凡作爲更新用我確實與同類型轉換嘗試如下,但它不工作插入它作爲一個正常的字符串 。

update dir_act set actname=?,acttype=?::enumcs,national_code=? where actcode=? 
+0

它必須是'acttype ='和'在準備statement'它轉換爲'enum' – Ashish

+0

@阿希什我曾嘗試與您的解決方案,但我得到org.postgresql .util.PSQLException:錯誤:類型「枚舉」不存在 –

回答

1

從JDBC的角度來看,只要將PostgreSQL枚舉視爲一個字符串即可。

引用博客Convert between Java enums and PostgreSQL enums

PostgreSQL allows you to create enum types using the following syntax:

CREATE TYPE animal_type AS ENUM('DOG', 'CAT', 'SQUIRREL'); 

You can now use ‘animal’ as a datatype in your tables, for example:

create table pet (       
    pet_id  integer   not null, 
    pet_type  animal_type  not null, 
    name   varchar(20)  not null 
); 

In Java, you’d have a corresponding enum type:

public enum AnimalType { 
    DOG, 
    CAT, 
    SQUIRREL; 
} 

Converting between Java and PostgreSQL enums is straightforward. For example, to insert or update an enum field you could use the CAST syntax in your SQL PreparedStatement:

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

Postgres will also let you insert/update an enum just by passing its value as a string.

Whether casting or not, the Java side is the same. You would set the fields like this:

stmt.setInt(1, 1); 
stmt.setString(2, AnimalType.DOG.toString()); 
stmt.setString(3, 'Rex'); 

Retrieving the enum from a SELECT statement looks like this:

AnimalType.valueOf(stmt.getString("pet_type")); 

Take into consideration that enums are case-sensitive, so any case mismatches between your Postgres enums and Java enums will have to be accounted for. Also note that the PostgreSQL enum type is non-standard SQL, and thus not portable.