Java 使用jdbc将枚举值保存并读取到数据库?
我使用JDBC在数据库中输入和获取类。在其中一个类中,我在Status字段中使用enum值 记录:Java 使用jdbc将枚举值保存并读取到数据库?,java,jdbc,Java,Jdbc,我使用JDBC在数据库中输入和获取类。在其中一个类中,我在Status字段中使用enum值 记录: private void writeOrder(List<Order> order) throws SQLException { PreparedStatement pst = connection.prepareStatement("insert into \"Order\" (id,customerId,date,status,totalCost) v
private void writeOrder(List<Order> order) throws SQLException {
PreparedStatement pst = connection.prepareStatement("insert into \"Order\" (id,customerId,date,status,totalCost) values(?, ?, ?, ?, ?)");
for (Order a : order) {
pst.setObject(1, a.getId());
pst.setObject(2, a.getDate());
pst.setObject(3, a.getStatus());
pst.execute();
}
录制时,我收到以下错误:org.postgresql.util.psqleexception:无法推断要用于ru.sfedu.schooldemies.model.OrderStatus实例的SQL类型。使用带有显式类型值的setObject()指定要使用的类型
但我怀疑我读错了。如何写入和读取enum类的字段?使用
状态enum作为字符串(varchar),这要感谢enum
中的方法:
要编写它,请使用a.getStatus().name()
:
pst.setObject(3,a.getStatus().name())代码>
要读取它,请使用Status.valueOf(rs.getString())
将其用作字符串(varchar):要写入它,请使用a.getStatus().name()
。要阅读它,请使用Status.valueOf(rs.getString())
@Arnaud它工作了!多谢各位much@Arnaud考虑把它作为答案。
private Object dataFromResultSet(ResultSet rs, Class aClass) throws SQLException{
return new Order(
rs.getLong(1),
rs.getTimestamp(2),
rs.getString(4),
);
}