我想用以下内容写入 MySQL 日期列值
jsonWriter.value((java.sql.Date) resultSet.getObject(column));
但是好像这是不可能的。它说long、Date、String都不适用于该类型。我怎样才能实现这个目标?
完整代码:
private static void writeField(final ResultSet resultSet, final JsonWriter jsonWriter, final ResultSetMetaData metaData, final int column) throws SQLException, IOException {
final int columnType = metaData.getColumnType(column);
switch ( columnType ) {
case Types.BIT:
case Types.TINYINT:
case Types.SMALLINT:
throw new UnsupportedOperationException("TODO: " + JDBCType.valueOf(columnType));
case Types.INTEGER:
jsonWriter.value((Integer) resultSet.getObject(column));
break;
case Types.BIGINT:
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
case Types.NUMERIC:
case Types.DECIMAL:
case Types.CHAR:
throw new UnsupportedOperationException("TODO: " + JDBCType.valueOf(columnType));
case Types.VARCHAR:
jsonWriter.value((String) resultSet.getObject(column));
break;
case Types.LONGVARCHAR:
jsonWriter.value((String) resultSet.getObject(column));
break;
case Types.DATE:
// here's the problem. i dont know to what to case the column.
jsonWriter.value((java.sql.Date) resultSet.getObject(column));
break;
case Types.TIME:
case Types.TIMESTAMP:
jsonWriter.value((long) resultSet.getObject(column));
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.NULL:
case Types.OTHER:
case Types.JAVA_OBJECT:
case Types.DISTINCT:
case Types.STRUCT:
case Types.ARRAY:
case Types.BLOB:
case Types.CLOB:
case Types.REF:
case Types.DATALINK:
case Types.BOOLEAN:
case Types.ROWID:
case Types.NCHAR:
case Types.NVARCHAR:
case Types.LONGNVARCHAR:
case Types.NCLOB:
case Types.SQLXML:
case Types.REF_CURSOR:
case Types.TIME_WITH_TIMEZONE:
case Types.TIMESTAMP_WITH_TIMEZONE:
throw new UnsupportedOperationException("TODO: " + JDBCType.valueOf(columnType));
default:
throw new UnsupportedOperationException("Unknown type: " + columnType);
}
}
我还需要稍后实现时间戳 - 以防它们相关。
非常感谢! :)
最佳答案
好吧,我终于找到了如何做到这一点(我希望不是 100% 确定,因为我还无法在客户端上显示数据 - 但它可以编译并运行。这是代码:
case Types.DATE:
java.sql.Date sqlDate = (java.sql.Date) resultSet.getObject(column);
LocalDate localDate = sqlDate.toLocalDate();
DateTimeFormatter formatDt = DateTimeFormatter.ISO_LOCAL_DATE;
String formattedDate = localDate.format(formatDt);
jsonWriter.value((String) formattedDate);
break;
我希望我没有以同样的方式格式化它两次? :)
这里还有时间戳的代码:
case Types.TIMESTAMP:
java.sql.Timestamp sqlTimeStamp = (java.sql.Timestamp) resultSet.getObject(column);
LocalDateTime localDateTime = sqlTimeStamp.toLocalDateTime();
DateTimeFormatter formatTimestamp = DateTimeFormatter.ISO_LOCAL_DATE;
String formattedDateTime = localDateTime.format(formatTimestamp);
jsonWriter.value((String) formattedDateTime);
break;
关于java - MySQL 结果集 JsonWriter : jsonWriter. value((java.sql.Date) resultSet.getObject(column));,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42664383/