Craiten
Craiten

Reputation: 109

Java sql - How to insert TimeStamp into a mysql database including milliseconds

How do I convert a Java TimeStamp object to a SQL datetime type that includes milliseconds? When I insert my TimeStamp obj into the database the milliseconds are gone.

This is my Java source code to translate a String into a Timestamp object:

import java.sql.Timestamp;
...
...
String timeStr = "2013-08-30 19:11:49.113";
Timestamp timeCreated = Timestamp.valueOf(timeStr);
timeCreated.toString(); //returns "2013-08-30 19:11:49.113"

My table dfinition in SQL:

CREATE TABLE `Event` (EventTimeStamp datetime NOT NULL);

This is how I insert the TimeStamp object into my Database:

PreparedStatement psInsert;
Connection conn = ...
psInsert = conn
            .prepareStatement("INSERT INTO `Event` (EventTimeStamp) VALUES(?)");  

psInsert.setTimestamp(1, timeCreated);
psInsert.executeUpdate();

After insertion the TimeStamp is cut and there are no milliseconds anymore:

2013-08-30 19:11:49

Thx

Upvotes: 4

Views: 3643

Answers (1)

Rob
Rob

Reputation: 6507

Your database column datetime has no place for milliseconds. You should use datetime(3) instead.

Upvotes: 2

Related Questions