如何在MySql时间戳中存储java日历时间?
我正在实现Java“忘记密码功能”,需要在重置密码页面中添加过期时间。我为time创建了一个Calendar类对象,并在其中添加了30分钟。代码如下:如何在MySql时间戳中存储java日历时间?,java,mysql,datetime,Java,Mysql,Datetime,我正在实现Java“忘记密码功能”,需要在重置密码页面中添加过期时间。我为time创建了一个Calendar类对象,并在其中添加了30分钟。代码如下: java.util.Date utilDate = new java.util.Date(); Calendar cal = Calendar.getInstance(); cal.setTime(utilDate); cal.add(Calendar.MINUTE, 30); 并在DB查询中使用为: String query = "INSER
java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.add(Calendar.MINUTE, 30);
并在DB查询中使用为:
String query = "INSERT INTO forgotpasskeytab (keyId, emailid, expireIn) VALUES ('"+uniqueID+"','"+emailid+"','"+cal.getTime()+"')";
myforgotpasskeytab
表中的expireIn列的类型为时间戳
我在运行时遇到以下错误:
com.mysql.jdbc.MysqlDataTruncation:数据截断:第1行“expireIn”列的日期时间值不正确:“Fri Oct 09 20:39:14 IST 2015”
有没有其他更好的方法来节省mysql DB表中的过期时间?通过将每个部分连接在一起来停止生成SQL!这很容易发生,而且被认为是一种非常糟糕的做法 您需要将a与
?
占位符()一起使用
假设变量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();
}
永远不要使用字符串连接在SQL中插入文本值,除非你想让自己受到攻击,允许黑客删除或窃取你的所有数据。改用
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();
}
mysql的格式是:yyyy-MM-dd-HH:MM:ss
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
然而,我同意prepared语句是一种更好的方法为了让查询正常工作,您需要java.sql.timestamp的timestamp实例,而您的'cal.getTime()'返回的java.util.Date实例是错误的 因此,以下查询适用于您的案例:
String query = "INSERT INTO forgotpasskeytab (keyId, emailid, expireIn) VALUES ('"+uniqueID+"','"+emailid+"','"+ new java.sql.Timestamp(cal.getTime()) +"')";
我看你也更喜欢写
新java.sql.Timestamp
而不是导入Timestamp
:)@Tunaki事实上,这是一个更大的问题,因为我最初要写的是java.sql.Date
,必须记录差异。当,你比我快了几秒钟。仅供参考:cal.getTimeInMillis()
在这种情况下更好。;-)感谢您的指导,但我想知道为什么要在“cal.getTime().getTime()”中练习.getTime()?@HarshVardhan,因为cal.getTime()
返回一个Date
,所以我们需要在此日期再次调用getTime()
,以获得一个long
值。但是可以使用更简单的cal.getTimeInMillis()
。