-1

i tried to store in two column current data and time on my microsft access database from java, but when i open my file no data has been stored. I tried to print the columns but it print "null". How can i do?

Date date = new Date();
final String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(date.getTime());
final String formattedTime = new SimpleDateFormat("HH:mm:ss").format(date.getTime());
final java.sql.Date sqlDate = java.sql.Date.valueOf(formattedDate);
final java.sql.Time sqlTime = java.sql.Time.valueOf(formattedTime);

...

PreparedStatement ps=con.prepareStatement("insert into Table1(Data) values(?)");
ps.setDate(1,sqlDate);
ps=con.prepareStatement("insert into Table1(Hour) values(?)");
ps.setTime(1,sqlTime);
ps.executeUpdate();

This is the printed result :

ID Name Date Hour
0001 Mary null null
  • I don't see any evidence that you've executed these statements, and this should probably be an update if you're trying to update the row. – Compass Apr 27 '18 at 18:31
  • Have you called `ps.executeUpdate()`? And possibly `con.commit()` if you switched off autocommit. – Ivan Apr 27 '18 at 18:31
  • Yes, i have called both but nothing changes. @Ivan – Miriam Younes Apr 27 '18 at 18:37
  • In your case you call `executeUpdate()` only for the second `PreparedStatement` which inserts into column `Hour`. Are there any exceptions thrown? – Ivan Apr 27 '18 at 18:42
  • 1
    @Ivan There's only this error: `WARNING:routine signature not found for: PUBLIC.FORMULATODATE(INTERVAL DAY TO SECOND,CHARACTER)` – Miriam Younes Apr 27 '18 at 18:43
  • 1
    Ok I got it! I've called `executeUpdate()` only for the last statement Thank you very much! @Ivan – Miriam Younes Apr 27 '18 at 18:47

1 Answers1

0

A couple of points:

  • As far as I can tell, there is no point in keeping your date and your time in two separate columns in your database table. I would use one column of datatype datetime.
  • The classes java.util.Date, SimpleDateFormat, java.sql.Date and Time are long outdated and poorly designed. Better to use java.time, the modern Java date and time API. It is so much nicer to work with.

Taking for granted that date and time are in separate columns your code may look like this:

    LocalDateTime dateTimeNow = LocalDateTime.now(ZoneId.of("Europe/Rome"));
    LocalDate dateToday = dateTimeNow.toLocalDate();
    LocalTime timeNow = dateTimeNow.toLocalTime();
    PreparedStatement ps 
            = con.prepareStatement("insert into Table1(Data, Hour) values(?, ?)");
    ps.setObject(1, dateToday);
    ps.setObject(2, timeNow);
    ps.executeUpdate();

This will insert one row containing both the current day and the current time. Please use your desired time zone where I put Europe/Rome since both date and time depend on time zone.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117