3

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

3
  • DateTime and Timestamp are not the same, this might be where your error is coming from Commented Apr 7, 2015 at 14:27
  • Try to print out original error message - it can contain some useful information. Commented Apr 7, 2015 at 14:31
  • Check this out stackoverflow.com/a/3323870/579580 most likely you will find your answer there Commented Apr 7, 2015 at 14:33

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.