Insert “daterange” field value into PostgreSQL table through JDBC

主宰稳场 提交于 2019-12-10 13:32:12

问题


I have a table in PostgreSQL(9.3) with daterange field type.

I can select this field like a String with JDBC, but I cannot Insert it in a table.

What I've tried:

PreparedStatement stm = conn.prepareStatement("insert into mytable (my_daterange_field) values (?)"); 
stm.setString(1, "[2014-01-02,2014-01-04]");
int i = stm.executeUpdate();

and I got:

Exception in thread "main" org.postgresql.util.PSQLException: ERROR: column "my_daterange_field" is of type daterange but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
  Position: 168

Does anyone have a solution for inserting daterange? What stm.setXXX should I use? Or maybe I cannot do that because JDBC Driver does not have daterange support... Maybe there is a third solution?

Thank you.

P.S.

My PostgreSQL JDBC Driver:

    <dependency>
      <groupId>postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>8.4-701.jdbc4</version>
    </dependency>

回答1:


Use:

insert into mytable (my_daterange_field) values (?::daterange)


来源:https://stackoverflow.com/questions/22218268/insert-daterange-field-value-into-postgresql-table-through-jdbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!