Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert "daterange" field value into PostgreSQL table through JDBC

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>
like image 477
artem.pronchakov Avatar asked Mar 06 '14 07:03

artem.pronchakov


People also ask

Does JDBC work with PostgreSQL?

JDBC APIs make use of JDBC drivers to get access to databases like PostgreSQL. JDBC APIs other than accessing the tabular data, also enable you to perform operations on the databases. You can perform save, update, delete, and fetch operations on the data stored in any database using JDBC.

What is Postgres JDBC?

The PostgreSQL JDBC Driver allows Java programs to connect to a PostgreSQL database using standard, database independent Java code. pgJDBC is an open source JDBC driver written in Pure Java (Type 4), and communicates in the PostgreSQL native network protocol.


1 Answers

Use:

insert into mytable (my_daterange_field) values (?::daterange)
like image 116
Craig Ringer Avatar answered Oct 03 '22 17:10

Craig Ringer