Get the time value from the database and report an error: Java sql. Timestamp cannot be cast to java. lang.Long
1. Problem description
Convert the queried timestamp type data in the database into long type and report an error.
String type = result.getClass().getName(); if ("java.sql.Timstamp".equalsIgnoreCase(type)) { return new Date((Long) result); }
2. Solution
Because Java sql.Timestamp is Java util. Subclass of date;
So, just put Java sql.Timestamp to Java util.Date type is enough.
String type = result.getClass().getName(); if ("java.sql.Timestamp".equalsIgnoreCase(type)) { return (Date)result; }
Or convert the data to string type output:
String type = result.getClass().getName(); // Convert Timestamp type to String type (yyyy-MM-dd HH:mm:ss) if ("java.sql.Timestamp".equalsIgnoreCase(type)) { //java.sql.Timestamp processing logic return DateUtil.timeToYmdHmsString((Date)result); }
The dateutil tool class is as follows:
public class DateUtil { private static String defaultYmdHmsPattern = "yyyy-MM-dd HH:mm:ss"; /** * Convert Date to String, format: yyyy-MM-dd HH:mm:ss * @param date date type * @return String Date format string */ public static String timeToYmdHmsString(Date date) { SimpleDateFormat formatter = new SimpleDateFormat(defaultYmdHmsPattern); return formatter.format(date); } }