4

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

Craiten
  • 109
  • 1
  • 2
  • 12

1 Answers1

2

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

Rob
  • 6,247
  • 2
  • 25
  • 33
  • This did the trick! Thx! But I needed to install the latest mysql version for this solution. @Lashane thx for the advice to update my mysql. – Craiten May 16 '16 at 17:39