Search code examples
javasqldate-formatucanaccess

java ucanaccess data storing


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

Solution

  • 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.