【问题标题】:How to store java Calendar time in MySql timestamp?如何在 MySql 时间戳中存储 java 日历时间?
【发布时间】:2016-01-07 13:45:03
【问题描述】:

我正在实现 Java“忘记密码功能”,需要在重置密码页面中添加过期时间。我为时间创建了一个日历类对象并添加了 30 分钟。代码如下:

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.add(Calendar.MINUTE, 30);

在数据库查询中用作:

String query = "INSERT INTO forgotpasskeytab (keyId, emailid, expireIn) VALUES ('"+uniqueID+"','"+emailid+"','"+cal.getTime()+"')";

forgotpasskeytab 表中的 expireIn 列的类型为 timestamp

运行时出现以下错误:

com.mysql.jdbc.MysqlDataTruncation:数据截断:不正确的日期时间值:'Fri Oct 09 20:39:14 IST 2015' for column 'expireIn' at row 1

还有其他更好的方法来节省mysql数据库表中的过期时间吗?

【问题讨论】:

    标签: java mysql datetime


    【解决方案1】:

    通过将每个部分连接在一起来停止生成 SQL!这很容易出现SQL injection,被认为是一种非常糟糕的做法。

    您需要使用 PreparedStatement? 占位符 (tutorial)。

    假设我们在变量connection 中有一个Connection 实例:

    try (PreparedStatement ps = connection.prepareStatement("INSERT INTO forgotpasskeytab (keyId, emailid, expireIn) VALUES (?,?,?)")) {
        ps.setLong(1, uniqueID); // the first value is replaced by uniqueID as Long
        ps.setLong(2, emailid); // the second value is replaced by emailid as Long
        ps.setTimestamp(3, new java.sql.Timestamp(cal.getTimeInMillis()));  // the third value is replaced by the timestamp of the calendar
        ps.executeUpdate();
    }
    

    【讨论】:

    • 该死,你领先我几秒。仅供参考:cal.getTimeInMillis() 在这种情况下更好。 ;-)
    • 感谢您的指导,但我想知道为什么要在 "cal.getTIme().getTime()" 中练习 .getTime() TWICE ??
    • @HarshVardhan 因为cal.getTime() 返回一个Date,所以我们需要在这个Date 上再次调用getTime() 以获得long 值。但是可以使用更简单的cal.getTimeInMillis()
    【解决方案2】:

    切勿使用字符串连接在 SQL 中插入文本值,除非您想让自己受到SQL Injection 攻击,从而允许黑客删除或窃取您的所有数据。请改用PrepareStatement

    这也有助于日期/时间值:

    String sql = "INSERT INTO forgotpasskeytab (keyId, emailid, expireIn) VALUES (?,?,?)";
    try (PreparedStatement stmt = conn.prepareStatement(sql)) {
        stmt.setString(1, uniqueID); // or setInt?
        stmt.setString(2, emailid); // or setInt?
        stmt.setTimestamp(3, new java.sql.Timestamp(cal.getTimeInMillis()));
        stmt.executeUpdate();
    }
    

    【讨论】:

    • 我看到你也更喜欢写new java.sql.Timestamp而不是导入Timestamp :)
    • @Tunaki 实际上,这更重要,因为我一开始打算使用 java.sql.Date,其中必须记录差异。
    【解决方案3】:

    mysql格式为:yyyy-MM-dd HH:mm:ss

    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
    

    不过我同意prepared statement是一个更好的方法

    【讨论】:

      【解决方案4】:

      为了让您的查询正常工作,您需要 java.sql.Timestamp 的时间戳实例,而您的 'cal.getTime()' 返回的 java.util.Date 实例是错误的。

      因此,以下查询应该适用于您的情况:

      String query = "INSERT INTO forgotpasskeytab (keyId, emailid, expireIn) VALUES ('"+uniqueID+"','"+emailid+"','"+ new java.sql.Timestamp(cal.getTime()) +"')";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-06
        相关资源
        最近更新 更多