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
实例.
归档时间: |
|
查看次数: |
3050 次 |
最近记录: |