I'm trying to insert a record to MySQL table using Java. My table schema:
CREATE TABLE records (
id int(5) NOT NULL,
value varchar(30) NOT NULL,
recorded_time timestamp(3) NOT NULL
);
My code to insert record in MySQL:
for (Record rec : records) {
st.setInt(1, rec.getId());
st.setString(2, rec.getValue().toString());
Timestamp ts = new Timestamp(rec.getDatetime());
System.out.println("New Timestamp: " + ts);
st.setTimestamp(3, ts);
System.out.println("Insert Statement: " + st);
st.addBatch();
}
st.executeBatch();
where st
is the preparedstatement. Output:
New Timestamp: 2017-09-18 17:59:03.362
Insert statement: INSERT INTO records ( id, value, recorded_time ) VALUES (306,'72.7','2017-09-18 17:59:03')
Value of 'datetime' field is generated using ZonedDateTime in Java8:
ZonedDateTime.ofInstant(Instant.now(), ZoneOffset.UTC).toInstant().toEpochMilli();
My question is timestamp shows the millisecs when I print it. But why the millisecs (362) not stored in the table. How to fix it.
Similar question on stackoverflow: How to insert current time in MySQL using Java. But I don't know how to use it in my case.
EDIT: MySQL version - 10.1.6