错误 - 在 JFreeChart 中无法将 java.sql.Timestamp 转换为 java.sql.Date

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20130129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:22:30  来源:igfitidea点击:

Error - java.sql.Timestamp cannot be cast to java.sql.Date in JFreeChart

javasqljfreechart

提问by mussi89

While i'm retrieving data from my database to add to a chart using JFreeChart I get the error:

当我从我的数据库中检索数据以使用 JFreeChart 添加到图表时,我收到错误消息:

java.sql.Timestamp cannot be cast to java.sql.Date

I have four columns the first three are retrieved properly using a case but while going through the final column it goes to the correct case:

我有四列,前三列是使用案例正确检索的,但在浏览最后一列时,它会转到正确的案例:

case Types.TIMESTAMP: {

But then the error occurs on this part:

但是随后在这部分发生错误:

Date date = (Date) resultSet.getObject(column);

The data within the database is formatted like this (HH,MM,SS).

数据库中的数据格式如下(HH,MM,SS)。

Edit - Also would like to add this class is included with the JFreeCharts API - JDBCCategoryDataset.java

编辑 - 还想添加此类包含在 JFreeCharts API 中 - JDBCCategoryDataset.java

回答by Konstantin

Date date = new Date(((Timestamp)resultSet.getObject(column)).getTime());

回答by Java Devil

Firstly, dont use a java.sql.Datefor time - It will not yeild the result you want... unless you want your time to be set to 0 for the current timezone

首先,不要使用java.sql.Date时间 - 它不会产生你想要的结果......除非你希望当前时区的时间设置为 0

From Docs:

从文档:

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

为了符合 SQL DATE 的定义,java.sql.Date 实例包装的毫秒值必须通过在实例关联的特定时区中将小时、分钟、秒和毫秒设置为零来“标准化” .

Also why use ResultSet.getObjectand cast when you could just use ResultSet.getDate()or ResultSet.getTime()or ResultSet.getTimestamp()where you want to use either of the seocnd two.

还有为什么ResultSet.getObject在您可以使用ResultSet.getDate()ResultSet.getTime()ResultSet.getTimestamp()您想使用第二个两个中的任何一个时使用和强制转换。

Then if you must use a date object, make a java.util.Datelike so

然后,如果您必须使用日期对象,请java.util.Date像这样

java.util.Date yourDate = new java.util.Date(resultSet.getTimestamp("Column").getTime());

Or if it is in the database as the String "(HH,MM,SS)"then you might want to get a string and use a formatter like a SimpleDateFormat

或者,如果它在数据库中作为字符串,"(HH,MM,SS)"那么您可能想要获取一个字符串并使用格式化程序,如SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("(hh,MM,ss)");
Date aDate = sdf.parse(resultSet.getString("column");