Converting input date string to SQL date type

68 Views Asked by At

I have looked all over for this answer for a whole day but I'm not getting anywhere.

I have a string that is formatted like this:

dd/mm/yyyy

I want to enter this in to a SQL database

The database field (of type Date) shows the format as yyyy-mm-dd.

At the moment I have the following code:

    String inputDate = dateBookingEntry.getText();
    LocalDate interDate = LocalDate.now();
    interDate.parse(inputDate,DateTimeFormatter.ofPattern("dd/MM/yyyy"));
    java.sql.Date finalDate = java.sql.Date.valueOf(interDate);

When I enter the date 12/12/2020 as the string, I get the error message:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2020-01-29'

I don't get what I'm doing wrong, or how to fix it. I get that it's showing the current date and not the entered date, but even if that was the problem, why would it show an SQL Syntax error?

What should I change here for it to work?

EDIT:

The SQL insertion code to this table looks like this:

st.executeUpdate("INSERT INTO `fitnessClasses`(`session`, `date`, `price`, `trainer`, `level`, `type`) VALUES ('"+session+"', '"+sqlDate+"', '"+price+"', '"+trainer+"', '"+level+"', '"+classType+"')");

The full SQL code mentioned above with the error looks like this:

ResultSet result = st.executeQuery("SELECT * FROM `fitnessClasses` WHERE `session` = '"+session+"' AND `date` '"+finalDate+"' AND `type` = '"+classType+"' AND `level` = '"+level+"'");

EDIT 2:

OK, I now realise I was missing an =.

Now the SQL SELECT works but it searches for today's date and not the entered date

1

There are 1 best solutions below

0
AstarAndy On

I think you want the class-level of parse such as

LocalDate interDate = LocalDate.parse(inputDate blah blah)

Currently you are setting interDate to now() which is the current date and that is why you end-up with today's date and not the date entered.