问题
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