Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java sql - insert timestamp into sql database

Tags:

java

sql

mysql

I'm trying to insert a timestamp into a database, but my code throws an exception, which tells me it's something with my sql statement.

The exception message shown is:

"Fout in Rit_ToevoegenController.okKnop(): SQLException in RitDB.voegRitToe() - statement"

okKnop is a different method that calls voegRitToe().

The type of the column called 'starttijd' is TIMESTAMP, and the DB Data type is DateTime.

i'm fairly certain that it's the timestamp that causes problems, because the other 2 are just a String and an int.

Any help with making it work would be greatly appreciated. I need to insert both the time and date into the database for comparing later.

public void voegRitToe(Rit r) throws DBException{
    Timestamp starttijd = new Timestamp(System.currentTimeMillis());
    //Date date = new Date(starttijd.getTime());

    try(Connection conn = ConnectionManager.getConnection();){
        try(PreparedStatement stmt = conn.prepareStatement("insert into rit(starttijd, lid_rijksregisternummer, fiets_registratienummer) values(?,?,?)");){
            stmt.setTimestamp(1, starttijd);
            stmt.setString(2, r.getLid().getRegisterNr());
            stmt.setInt(3, r.getFiets().getRegisNr());
            stmt.execute();
        }
        catch(SQLException sqlEx){
            throw new DBException("SQLException in RitDB.voegRitToe() - statement");
        }

    }
    catch(SQLException sqlEx){
        throw new DBException("SQLException in RitDB.voegRitToe() - verbinding");
    }
}

enter image description here

like image 264
MichaelD Avatar asked Sep 27 '26 21:09

MichaelD


1 Answers

TIMESTAMP and DATETIME serve different purposes; TIMESTAMP is for automatic time stamping.

java.util.Date starttijd = new java.util.Date(System.currentTimeMillis());
java.util.Date starttijd = new java.util.Date(); // Or this

I guess you came at Timestamp, as java.sql.Date wraps java.util.Date by setting the time part to zero!

If the database server's time is correct, one could also do:

... VALUES(NOW(), ?, ?)

By the way, java 8 introduces new date/time classes and "improve" upon the JDBC usage, if you have a java 8 compliant driver.

like image 82
Joop Eggen Avatar answered Sep 29 '26 11:09

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!