我有一个 Java 枚举:
public enum Equipment { Hood, Blinkers, ToungTie, CheekPieces, Visor, EyeShield, None;}
和相应的 Postgres 枚举:
CREATE TYPE equipment AS ENUM ('Hood', 'Blinkers', 'ToungTie', 'CheekPieces', 'Visor', 'EyeShield', 'None');
在我的数据库中,我有一个表,其中有一列包含“设备”项目的数组:
CREATE TABLE "Entry" (
id bigint NOT NULL DEFAULT nextval('seq'::regclass),
"date" character(10) NOT NULL,
equipment equipment[]
);
最后,当我运行我的应用程序时,我有一个“设备”枚举数组,我想使用准备好的语句将其持久保存到数据库中,但我一直不知道该怎么做.
StringBuffer sb = new StringBuffer("insert into \"Entry\" ");
sb.append("( \"date\", \"equipment \" )");
sb.append(" values ( ?, ? )");
PreparedStatement ps = db.prepareStatement(sb.toString());
ps.setString("2010-10-10");
ps.set???????????
最佳答案
你应该阅读 this .
我建议您的代码看起来更像这样:
// A column named "date" is probably illegal and not very illustrative. "date" is a keyword for most databases.
// Building a string that never changes again and again is a waste of CPU and heap
private static final String INSERT_SQL = "insert into Entry(date,equipment) values(?,?)";
PreparedStatement ps = db.prepareStatement(INSERT_SQL);
// Use the type system properly. Dates should be DATE type columns in a database. Why string?
ps.setDate(entryDate);
// You shouldn't want to insert an array of values; that's not normalized.
ps.setString(equipmentEnumValue.name());
关于java - 使用 PreparedStatement 将 Java 枚举数组持久化到 Postgres 枚举数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2917286/