Java JDBC结果集检索LocalDateTime
我运行一个简单的查询,从MySQL数据库中检索一行。 我得到Java JDBC结果集检索LocalDateTime,java,mysql,jdbc,java-time,Java,Mysql,Jdbc,Java Time,我运行一个简单的查询,从MySQL数据库中检索一行。 我得到ResultSet,需要从中检索LocalDateTime对象。 我的DB表 CREATE TABLE `some_entity` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `title` varchar(45) NOT NULL, `text` varchar(255) DEFAULT NULL, `created_date_time` datetime NOT NULL,
ResultSet
,需要从中检索LocalDateTime对象。
我的DB表
CREATE TABLE `some_entity` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(45) NOT NULL,
`text` varchar(255) DEFAULT NULL,
`created_date_time` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
我需要按id检索某个实体
String SELECT = "SELECT ID, TITLE, TEXT, CREATED_DATE_TIME FROM some_entity WHERE some_entity.id = ?";
PreparedStatement selectPreparedStatement = connection.prepareStatement(SELECT);
try {
selectPreparedStatement.setLong(1, id);
ResultSet resultSet = selectPreparedStatement.executeQuery();
if (resultSet.next()) {
Long foundId = resultSet.getLong(1);
String title = resultSet.getString(2);
String text = resultSet.getString(3);
LocalDateTime createdDateTime = null;// How do I retrieve it???
}
} catch (SQLException e) {
throw new RuntimeException("Failed to retrieve some entity by id.", e);
}
尝试将此作为检索,然后转换为使用:
编辑:正如中所指出的,在使用最新的JDBC驱动程序时,有一个更好的解决方案:
resultSet.getObject(4,LocalDateTime.class)
这将跳过创建冗余的
java.sql.Timestamp
实例。这可能会有所帮助,我明白了。1) 从resultSet中检索时间戳,2)将其转换为LocalDateTime…如果JDBC驱动程序是合理的最新版本,并且已经更新为使用Java 8,那么您应该能够使用resultSet.getObject(4,LocalDateTime.class)
即使我对MySQL使用DateTime,我也应该调用getTimestamp()
?不是getDate()
?没有时间组件:“为了符合SQLDATE
的定义,必须通过将实例关联的特定时区中的小时、分钟、秒和毫秒设置为零来“规范化”由java.SQL.DATE
实例包装的毫秒值。”不过,我不保证java.sql.Timestamp
会起作用,但它似乎是java.sql
包中表示日期时间的唯一类型。对于编辑来说,+1。它还避免了时间戳可能损坏某些日期/时间值的问题,例如,2018-03-11 02:00:00
(美国/多伦多的凌晨2点)将神奇地更改为凌晨3点。resultSet.getObject(4,LocalDateTime.class)
使用postgres和最新的jdbc库对我不起作用resultSet.getTimestamp(4.toLocalDateTime()
确实有效我最近尝试了这种技术。但是,即使上面的代码可以工作,MySQL驱动程序也存在一个错误,它将时区偏移错误地应用于LocalDateTime
值。从MySQL Connector Java 8.0.19版开始,此错误仍然存在。参考:
LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()