【问题标题】:Date Java to MySql DateTime将 Java 日期转换为 MySql 日期时间
【发布时间】:2011-11-24 13:50:20
【问题描述】:

每个人。我收到此错误: 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 '14:37:41)' at line 1 对于这段代码

       public String addName() {
    // TODO Auto-generated method stub
    try {
        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");

        String currentTime = sdf.format(dt);



        String name = "RandomName";

        Connection connect = DriverManager.getConnection(
                "jdbc:mysql://localhost", "ericman", "ericman");
        Statement stat = (Statement) connect.createStatement();
        String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES ('"
                + name + "', " + currentTime + ")";
        stat.executeUpdate(insert);

    } catch (Exception e) {
        System.out.println(e);
    }
    return "Name Updated";
}

任何关于为什么会发生这种情况的建议,我很讨厌结构化语言,只是为了让你知道 :)

【问题讨论】:

  • 在字符串中插入日期是错误的...

标签: java mysql networking date


【解决方案1】:

使用PreparedStatement。

String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES (?,?)";
PreparedStatement ps=connect.prepareStatement(insert);
ps.setString(1,name);
ps.setTimeStamp(2,TimeStamp.valueOf(currentTime));
ps.executeUpdate();

【讨论】:

    【解决方案2】:

    您在插入语句中的 currentTime 周围缺少 ' 字符。

    但是,您确实应该为此类事情使用准备好的语句,以防止 SQL 注入攻击。

    【讨论】:

      【解决方案3】:

      尝试通过str_to_date将字符串转换为日期

      【讨论】:

        【解决方案4】:

        您是否需要像使用 name 参数那样使用引号将日期/时间封装在 INSERT 语句中?

        【讨论】:

          【解决方案5】:

          呃。为什么不使用 PreparedStatement 代替?

          PreparedStatement stmt = connect.prepareStatement("INSERT INTO bookcatalog.puch(name, time) values ?,?");
          stmt.setString(1, name);
          stmt.setTimestamp(2, dt);
          stmt.execute();
          

          干净多了。

          【讨论】:

          • 我的 MySQL 语言很差。请您演示一下,您的代码将如何替换我的错误代码?谢谢!!
          • 见上面@AVD链接的例子。
          • 它说我应该转换时间戳,所以我做了。我看不到任何链接,也看不到 AVD 用户?谢谢!
          猜你喜欢
          • 1970-01-01
          • 2011-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-23
          • 2011-11-11
          相关资源
          最近更新 更多