【问题标题】:JDBC result set retrieve LocalDateTime [duplicate]JDBC结果集检索LocalDateTime [重复]
【发布时间】:2019-01-08 23:49:16
【问题描述】:

我运行一个简单的查询来从 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;

我需要通过 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);
}

【问题讨论】:

  • 是的,我明白了。 1) 从结果集中检索时间戳,2) 将其转换为 LocalDateTime...
  • 如果 JDBC 驱动程序是相当新的并且已经更新以与 Java 8 一起使用,那么您应该能够使用 resultSet.getObject(4, LocalDateTime.class)

标签: java mysql jdbc java-time


【解决方案1】:

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

LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()

编辑:正如Gord Thompsonhis comment 中指出的那样,使用最新的 JDBC 驱动程序时有一个更好的解决方案:

resultSet.getObject(4, LocalDateTime.class)

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

【讨论】:

  • 即使我使用 MySQL 的 DateTime,我也应该调用getTimestamp()?不是getDate()
  • java.sql.Date has no time component: "为了符合 SQL DATE 的定义,java.sql.Date 实例包装的毫秒值必须通过设置小时、分钟、秒,在与实例关联的特定时区中毫秒到零。”我不保证java.sql.Timestamp 会起作用,但它似乎是java.sql 包中唯一代表日期时间的类型。
  • +1 表示编辑。它还避免了时间戳可能破坏某些日期/时间值的问题,例如,America/Toronto 中的2018-03-11 02:00:00 (2 AM) 将神奇地更改为 3 AM。
  • resultSet.getObject(4, LocalDateTime.class) 使用 postgres 和最新的 jdbc 库对我不起作用。 resultSet.getTimestamp(4).toLocalDateTime() 确实有效
  • 我最近尝试了这种技术。然而,即使上面的代码应该可以工作,也有一个 MySQL 驱动程序错误,它错误地将时区偏移量应用于 LocalDateTime 值。自 MySQL 连接器 Java 版本 8.0.19 起,此错误仍然存​​在。参考:bugs.mysql.com/bug.php?id=93444
猜你喜欢
  • 2021-11-21
  • 1970-01-01
  • 2017-08-03
  • 2016-11-13
  • 2014-06-15
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多