2015-10-09 38 views
2

我正在實現Java「忘記密碼功能」,並需要在重置密碼頁面添加過期時間。我爲時間創建了一個Calendar類對象,並在其中添加了30分鐘。下面的代碼:如何在MySql時間戳中存儲java日曆時間?

而且在DB查詢作爲:

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

expireIn列在我的forgotpasskeytabtimestamp類型。

我收到以下錯誤運行時:

com.mysql.jdbc.MysqlDataTruncation:數據截斷:不正確的日期時間值: '週五09年10月20時39分14秒IST 2015年' 列「expireIn '在第1行

是否有任何其他更好的方法來保存mysql數據庫表中的過期時間?

回答

3

通過將每個部分連接在一起來停止生成您的SQL!這很容易出現SQL injection,被認爲是一種非常糟糕的做法。

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

假設我們有可變connectionConnection實例:

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(); 
} 
+0

黨,你幾秒打我。僅供參考:'cal.getTimeInMillis()'在這種情況下更好。 ;-) – Andreas

+0

@Andreas你說得對,我編輯了這個 – Tunaki

+0

感謝你的指導,但我想知道爲什麼在「cal.getTIme()。getTime()」中練習.getTime()TWICE。 –

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(); 
} 
+0

我看到你也更喜歡編寫'new java.sql.Timestamp'而不是導入'Timestamp' :) – Tunaki

+0

@Tunaki實際上,那是因爲我正在尋找'java.sql。日期「,首先需要記錄差異。 – Andreas

0

MySQL的格式爲:YYYY-MM-DD HH:MM:SS

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

不過,我同意,準備語句是一個更好的方法

0

爲了讓你的查詢工作,你需要一個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()) +"')";