代码之家  ›  专栏  ›  技术社区  ›  Yan Khonski

JDBC结果集检索localdatetime[重复]

  •  1
  • Yan Khonski  · 技术社区  · 6 年前

    我运行一个简单的查询从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 = 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 回复  |  直到 6 年前
        1
  •  7
  •   Tomasz Linkowski    6 年前

    java.sql.Timestamp LocalDateTime Timestamp.toLocalDateTime

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

    Gord Thompson his comment

    resultSet.getObject(4, LocalDateTime.class)