I keep getting this error
class java.time.format.Parsed cannot be cast to class java.time.LocalDate (java.time.format.Parsed and java.time.LocalDate are in module java.base of loader 'bootstrap')
I am trying to insert date and time values into my database.
My code:
String sTime = Helper.readString("Enter Closing Time (HH:MM:SS) > ");
try {
Time time = new Time(timeFormat.parse(sTime).getTime());
String sDate = Helper.readString("Enter Date (YYYY-MM-DD) > ");
LocalDate date = (LocalDate) dateFormat.parse(sDate);
String event = Helper.readString("Enter Event > ");
addStadium(id, name, category, time, date, event);
} catch (ParseException e) {
}
private void addStadium(String id, String name, String category, Time time, LocalDate date, String event) {
try {
String query = "INSERT INTO Stadium(ID, Name, Category, ClosingTime, DateUnavailable, Event) "
+ "SELECT J.ID,J.Name, J.Category, J.ClosingTime, U.DateUnavailable, U.Event FROM jogging_spot J INNER JOIN unavailability_date U ON J.ID = U.ID "
+ "VALUES('" + id + "', '" + name + "', '" + category + "', '" + time + ", " + date + ", '" + event + "')";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
+
to place values in the statement; useVALUES(?, ?, ?, ?, ?, ?)
instead, and use code likepstmt.setString(1, id);
,pstmt.setObject(5, date);
, and so on. In real world applications, building SQL statements using+
is very dangerous and is an extremely common reason for databases being hacked. You also should use java.time.LocalTime instead of the Time class; Time was an unfortunate design mistake which LocalTime corrects.java.sql.Time
. Don't usejava.text.DateFormat
andParseException
(if that's what you were trying). UseLocalTime.parse(sTime)
andLocalDate.parse(sDate)
to obtain aLocalTime
and aLocalDate
object that will go into your database. CatchDateTimeParseException
in case the user types an incorrect time or date. And don't ever in your life leave yourcatch
block empty: do make yourself and your user aware when something goes wrong.LocalTime
in much the same way asLocalDate
is handled in the answer there. Or even better, usedatetime
in your database andLocalDateTIme
in Java and still in much the same way.