简体   繁体   English

将输入日期字符串转换为 SQL 日期类型

[英]Converting input date string to SQL date type

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我想将此输入到 SQL 数据库中

The database field (of type Date) shows the format as yyyy-mm-dd.数据库字段(日期类型)将格式显示为 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:当我输入日期 12/12/2020 作为字符串时,我收到错误消息:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; java.sql.SQLSyntaxErrorException:您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2020-01-29'检查与您的 MySQL 服务器版本相对应的手册,了解在“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?我知道它显示的是当前日期而不是输入的日期,但即使这是问题,为什么它会显示 SQL 语法错误?

What should I change here for it to work?我应该在这里更改什么才能使其正常工作?

EDIT:编辑:

The SQL insertion code to this table looks like this:此表的 SQL 插入代码如下所示:

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:上面提到的带有错误的完整 SQL 代码如下所示:

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

EDIT 2:编辑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现在 SQL SELECT 工作但它搜索今天的日期而不是输入的日期

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.当前,您将 interDate 设置为 now(),这是当前日期,这就是您以今天的日期而不是输入的日期结束的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM