What java object to use to insert a date in a PostgreSQL timestamp field

1

I am working with a PostgreSQL database , in which I have a field of type timestamp since I only want a date with its time (no time zone ).

To do the saving I am making use of the object LocalDateTime of Java 8.

The question is, is it good practice to do it using that object, or should we use the Date object in the java.sql package?

    
asked by AlvaroRM 23.07.2018 в 12:30
source

2 answers

3

Let's review the options:

  • The class java.sql.Date , as its name indicates, only saves the date, but without the time. We should not confuse it with java.util.Date .
  • Class java.sql.Timestamp extends java.util.Date , making it more accurate by saving up to nanoseconds.

Therefore the pre-Java 8 option would be java.sql.Timestamp .

With Java 8 or higher:

The PostgreSQL documentation directs towards the use of LocalDate (for DATE type) ) and LocalDateTime (For type TIMESTAMP):

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
while (rs.next()) {

   LocalDateTime ts = rs.getObject(1, LocalDateTime.class));
   System.out.println(ts);
} 
rs.close();
st.close();
    
answered by 23.07.2018 / 13:29
source
0

Because you do not use the Timestamp class that is also in Java, it would be the right thing to do

link

    
answered by 23.07.2018 в 12:34