首先,我试图在我的 mysql 数据库中以毫秒精度插入时间戳,我通过这段代码获得了成功:
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());
}
为此,我在数据库中的表是:
CREATE TABLE `test_table` (
`id` INT NOT NULL AUTO_INCREMENT,
`timestamp` TIMESTAMP(3) NOT NULL,
PRIMARY KEY (`id`));
instant.toEpochMilli()
这是来自我的 java 代码和timestamp
来自我的数据库的毫秒数:
毫秒:1564566174331 和时间戳:2019-07-31 15:27:54.331
现在我想在我的 java 代码中检索这个时间戳,因此我的代码是:
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());
}
但是我得到的总时间戳(以毫秒为单位)是:
毫秒:1564566174000
不知何故,331
以毫秒为单位的值消失了。
如何以毫秒精度检索完整的时间戳值。现在我越来越糊涂了。我错过了什么?
我尝试了什么:
A)我尝试使用 ResultSet 的 getTime() 获取时间戳以检索总时间(以毫秒为单位),如下所示:
LOG.info("milliseconds: {}", rs.getTimestamp("timestamp").getTime());
仍然没有检索到毫秒位置值。结果与上面相同。
B)我也尝试了 getObject() 并且令我惊讶的是,毫秒位置值以某种方式放置在 NANOSECONDS 位置。
LOG.info("object: {}", rs.getObject("timestamp").toString());
我得到了什么:
对象:2019-07-31 15:27:54.000000331