First of I was trying to insert timestamp in millisecond precision in my mysql database, which I got success by this code:
Instant instant = Instant.now().truncatedTo(ChronoUnit.MILLIS);
try (Connection conn = DbConnection.getCon();
PreparedStatement ps = conn.prepareStatement("INSERT INTO test_table (timestamp) VALUES (FROM_UNIXTIME(?*0.001))");) {
ps.setObject(1, instant.toEpochMilli());
ps.executeUpdate();
LOG.info("Instant: {} and long: {}", instant, instant.toEpochMilli());
} catch (SQLException ex) {
LOG.error(ex.getMessage());
}
For this my table in database is:
CREATE TABLE `test_table` (
`id` INT NOT NULL AUTO_INCREMENT,
`timestamp` TIMESTAMP(3) NOT NULL,
PRIMARY KEY (`id`));
This is my milliseconds from instant.toEpochMilli()
from my java code and timestamp
in from my database:
milliseconds: 1564566174331 and timestamp: 2019-07-31 15:27:54.331
Now I wanted to retrieve this timestamp in my java code hence my code is:
try (Connection conn = DbConnection.getCon();
PreparedStatement ps = conn.prepareStatement("SELECT timestamp FROM test_table WHERE id=?")) {
ps.setString(1, "14");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
LOG.info("milliseconds: {}", rs.getTimestamp("timestamp").toInstant().toEpochMilli());
} else {
LOG.info("No data");
}
} catch (SQLException ex) {
LOG.error(ex.getMessage());
}
But what I got for total timestamp in milliseconds for this is:
milliseconds: 1564566174000
Somehow that 331
value in millisecond place is gone.
How to RETRIEVE complete timestamp value in millisecond precision. Now I am getting more confused. What am I missing?
What I tried:
A) I tried getTime() of ResultSet for timestamp to retrieve total time in milliseconds as:
LOG.info("milliseconds: {}", rs.getTimestamp("timestamp").getTime());
Still not retrieving that milliseconds place value. Same result as above.
B) I tried getObject() as well and TO MY ASTONISHMENT the milliseconds place value is somehow placed at NANOSECONDS place.
LOG.info("object: {}", rs.getObject("timestamp").toString());
What I got:
object: 2019-07-31 15:27:54.000000331