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

谁都会走 提交于 2019-12-11 02:49:00

问题


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

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).

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


回答1:


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



回答2:


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

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.

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

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

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

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


来源:https://stackoverflow.com/questions/20130129/error-java-sql-timestamp-cannot-be-cast-to-java-sql-date-in-jfreechart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!