I'm working on a project that requires me to allow the user to select three different values from JComboBoxes, then take the selected values and create a record in a database table when a button is pressed. I'm having trouble when trying to insert the values into the record, as the first two are strings, and the third is a date.
When the button is pressed, the method to add the record is called, sending the values to that method to be added.
Below is the constructor code for adding the record:
public BookingQueries()
{
//Establish database connection
getConnection();
BookingEntry entry = new BookingEntry();
try
{
insertNewBooking = connection.prepareStatement("INSERT INTO Bookings (Customer, Flight, Day) VALUES(?,?,?)");
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
System.exit(1);
}
}
This is the code in the method being called to add the record:
public void addBooking(String customer, String flight, Date day)
{
try {
insertNewBooking.setString(1,customer);
insertNewBooking.setString(2, flight);
insertNewBooking.setDate(3, (java.sql.Date) day);
insertNewBooking.executeUpdate();
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
}
I'm getting an exception saying "java.lang.String cannot be cast to java.util.date".
I'm fairly new to working with databases in Java, but the way that I'm interpreting that is the issue is with adding the "Date" value, which should be added to the SQL database as a Date type. If someone can provide some insight as to how to fix this or corrections to my thinking that I'm just overseeing, it'd be greatly appreciated.
EDIT:
Here is the database table that I'm trying to add to:
The console says that the error is being caused in the ActionPerformed method when the button is pressed. This is the code for that:
private void bookingBtnActionPerformed(java.awt.event.ActionEvent evt) {
Customer customer = new Customer();
Flight flight = new Flight();
Day day = new Day();
BookingEntry entry = new BookingEntry();
BookingQueries booking = new BookingQueries();
String selectedCustomer = (String) customerComboBox.getSelectedItem();
entry.setCustomer(selectedCustomer);
String selectedFlight = (String) flightComboBox.getSelectedItem();
entry.setFlight(selectedFlight);
Date selectedDate = (Date) dayComboBox.getSelectedItem();
entry.setDay(selectedDate);
booking.addBooking(entry.getCustomer(),entry.flight(),entry.day());
}
Specifically at this line:
Date selectedDate = (Date) dayComboBox.getSelectedItem();