JDBC 结果集检索 LocalDateTime
JDBC result set retrieve LocalDateTime
我 运行 从 MySQL 数据库中检索一行的简单查询。
我得到 ResultSet
并且我需要从中检索一个 LocalDateTime 对象。
我的数据库 table.
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);
}
尝试将其检索为 java.sql.Timestamp
and then converting to LocalDateTime
using Timestamp.toLocalDateTime
:
LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()
编辑:与Gord Thompson pointed out in 一样,使用足够新的JDBC驱动程序时有更好的解决方案:
resultSet.getObject(4, LocalDateTime.class)
这将跳过创建冗余 java.sql.Timestamp
实例。
我 运行 从 MySQL 数据库中检索一行的简单查询。
我得到 ResultSet
并且我需要从中检索一个 LocalDateTime 对象。
我的数据库 table.
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);
}
尝试将其检索为 java.sql.Timestamp
and then converting to LocalDateTime
using Timestamp.toLocalDateTime
:
LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()
编辑:与Gord Thompson pointed out in
resultSet.getObject(4, LocalDateTime.class)
这将跳过创建冗余 java.sql.Timestamp
实例。