4

I am wanting to insert a datetime into a MySql data base using Java and a prepared statement:

Calendar cal = Calendar.getInstance();
PreparedStatement stmnt = db.PreparedStatement("INSERT INTO Run " +
                       "(Time) VALUE (?) ");
    stmnt.setDate(1, new java.sql.Date(cal.getTime()));
    stmnt.executeQuery();  

NOTE: there is currently an error - cannot find symbol (java.sql.Date) line 4 here

db is an instance of a sort of wrapper class that exposes what I need from java.sql - its just getting a prepared statement from my connection object here.

Time (the column) is a date time in my database, and I can only see setDate and setTime method but I want to store both - also my code does not work anyway ;-)

If anyone could give me some pointers on inserting a combined date time (current time would be a great help as that's my first goal) into a MySql DB using a prepared statement I would be very grateful.

Thanks

2 Answers 2

5

The constructor for java.sql.Date takes a long (milliseconds since 1970) java.sql.Date To get milliseconds from a java.uitl.Calendar, you use cal.getTimeInMillis()

Your code would be:

Calendar cal = Calendar.getInstance();
PreparedStatement stmnt = db.PreparedStatement("INSERT INTO Run " + "(Time) VALUE (?) ");
stmnt.setDate(1, new java.sql.Date(cal.getTimeInMillis()));
stmnt.executeQuery();
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! thats the problem, stange how the error seemed so unrelated. Thank you very much for your help.
2

the following code should allow you to insert a date with millisecond accuracy. I have used it with HSQLDB, Sybase, SQL-Server and MySql without any problems.

java.util.Date date = getMyDate();
if (date == null) {
    statement.setNull(insertionIndex, Types.TIMESTAMP);
} else {
    statement.setTimestamp(insertionIndex, new Timestamp (date.getTime()));
}

Comments

Your Answer

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