使用JdbcTemplate的rowMapper方法,在实现mapRow方法中使用SimpleDateFormat格式化Date类型数据,并将其转换为String类型返回。
示例代码:
public class MyDateMapper implements RowMapper<String> {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = rs.getDate("date_field");
return formatter.format(date);
}
}
// 使用示例
String sql = "SELECT date_field FROM my_table WHERE id = ?";
String dateString = jdbcTemplate.queryForObject(sql, new Object[] { id }, new MyDateMapper());