JDBC结果集检索LocalDateTime

Yan*_*ski 4 java mysql jdbc java-time

我运行一个简单的查询来从MySQL数据库中检索一行.我得到了ResultSet,我需要从中检索一个LocalDateTime对象.我的数据库表.

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;
Run Code Online (Sandbox Code Playgroud)

我需要通过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);
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ski 14

尝试将其检索为java.sql.Timestamp,然后转换为LocalDateTime使用Timestamp.toLocalDateTime:

LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()
Run Code Online (Sandbox Code Playgroud)

编辑:正如Gord Thompson他的评论中所指出的,当使用最近的JDBC驱动程序时,有一个更好的解决方案:

resultSet.getObject(4, LocalDateTime.class)

这会跳过创建冗余java.sql.Timestamp实例.

  • +1以进行编辑。它还避免了时间戳可能损坏某些日期/时间值的问题,例如,“美国/多伦多”中的“ 2018-03-11 02:00:00”(凌晨2点)将神奇地更改为凌晨3点。 (3认同)
  • 我最近尝试了这种技术。然而,即使上面的代码应该可以工作,但存在一个 MySQL 驱动程序错误,该错误错误地将时区偏移应用于“LocalDateTime”值。从 MySQL Connector Java 版本 8.0.19 开始,此错误仍然存​​在。参考:https://bugs.mysql.com/bug.php?id=93444 (2认同)