gpt4 book ai didi

java - 无法将日期添加到 SQL 数据库

转载 作者:行者123 更新时间:2023-11-29 07:06:42 25 4
gpt4 key购买 nike

我要将日期添加到数据库中。数据库字段的类型为 DATE,我传入一个包含日期的字符串。这是sql:

INSERT INTO timetableslot (TO_DATE('?', 'MM/DD/YYYY'), time, classID, cost)
VALUES ('12/23/2016','12:00',3,12)

我收到以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '('?', 'MM/DD/YYYY'), time, classID, cost)VALUES ('12/23/2016','12:00',3,12)' at line 1

public boolean saveToDatabase() {

boolean saved = false;
Connection c = DBHelperClass.getConnection();
String template = "INSERT INTO timetableslot (TO_DATE('?', 'MM/DD/YYYY'), time, classID, cost)"
+ "VALUES (?,?,?,?)";
if (c != null) {
try {
PreparedStatement inserter = c.prepareStatement(template);
inserter.setString(1, this.getDate());
inserter.setString(2, this.getTime());
inserter.setInt(3, this.getClassID());
inserter.setInt(4, this.getCost());

System.out.println(inserter);
inserter.executeUpdate();
saved = true;
} catch (SQLException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}

}

return saved;
}

最佳答案

使用以下内容作为您准备好的声明:

String template = "INSERT INTO timetableslot (<COLUMN-NAME>, time, classID, cost) VALUES (STR_TO_DATE(?, '%m/%d/%Y'),?,?,?)";

TO_DATE 是一个 Oracle 函数。 MySQL 使用STR_TO_DATE

关于java - 无法将日期添加到 SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41351035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com