我要将日期添加到数据库中。数据库字段的类型为 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/