【问题标题】:Can't add date to a sql database无法将日期添加到 sql 数据库
【发布时间】:2016-12-27 19:25:54
【问题描述】:

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

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

我收到以下错误:

您的 SQL 语法有错误;检查手册 对应于您的 MariaDB 服务器版本,以便使用正确的语法 '('?', 'MM/DD/YYYY'), 时间, classID, cost)VALUES 附近 ('12/23/2016','12:00',3,12)' 在第 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;
}

【问题讨论】:

  • 列名将代替TO_DATE('?', 'MM/DD/YYYY')

标签: java mysql sql jsp


【解决方案1】:

使用以下作为准备好的陈述:

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.SQLException: Parameter index out of range (4 > number of parameters, which is 3).
  • 嘿@Pavol,您是否将&lt;COLUMN-NAME&gt; 替换为您的日期列的名称?
  • 我有 是 String template = "INSERT INTO timetableslot (date, time, classID, cost) VALUES (STR_TO_DATE('?', '%m/%d/%y'),?,? ,?)";
  • 尝试从STR_TO_DATE 中的? 中删除撇号。导致STR_TO_DATE(?, '%m/%d/%y')。
猜你喜欢
  • 2015-10-31
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 2019-09-15
相关资源
最近更新 更多