我正在使用mysql 5.7.x
版本。我也在使用java 8。我正在尝试java.time.instant
从java代码将当前日期时间以毫秒精度插入到我的mysql数据库中。为此,我正在使用preparedstatement
.
我的数据库中的表是:
CREATE TABLE `test_table` (
`id` INT NOT NULL AUTO_INCREMENT,
`timestamp` TIMESTAMP(3) NOT NULL,
PRIMARY KEY (`id`));
我要插入的java代码是:
Instant instant = Instant.now().truncatedTo(ChronoUnit.MILLIS);
try (Connection conn = DbConnection.getCon();
PreparedStatement ps = conn.prepareStatement("INSERT INTO test_table (timestamp) VALUES (?)");) {
ps.setTimestamp(1, Timestamp.from(instant));
ps.executeUpdate();
LOG.info("Instant: {} and long: {}", instant, instant.toEpochMilli());
} catch (SQLException ex) {
LOG.error(ex.getMessage());
}
从我的日志中,我可以看到毫秒为:2019-07-30T10:52:34.865Z。但在我的 mysql 数据库中,它变成:2019-07-30 10:52:34.000Z
我在堆栈中搜索了很多问题和答案,但似乎没有一个对我有用。
更新1:
我尝试使用 setObject 作为:
ps.setObject(1, Timestamp.from(instant));
但还是一样的结果。无法检索数据库中的毫秒数。