2012-05-29 27 views
1

我需要使用Statement.executeUpdate()插入數據到數據庫。 因此,每個參數都必須嵌入到SQL字符串中。 在數據庫,兩列的類型是日期時間:日期1和date2 在客戶端,如果我用下面的語句:如何嵌入日期時間到SQL字符串

String SQLString = "INSERT INTO Position (" + 
    ...... 
    "Date1, " + 
    ...... 
    "Date2) " + 
    "VALUES(" + 
    ...... 
    //"2012-05-29 16:28:58.555" + ", " + // runtime error, always say error at 16 
    //"2012-05-29" + ", " + // no runtime error, but lost time and result date is also not correct 
    //"10-06-02" + ", " + // no runtime error, but it adds 2 days beginning at 1900-01-01 00:00:00.000 
    ...... 
    null 
    ")"; 

誰能告訴我如何正確地嵌入到日期時間SQL字符串?

+0

類似於:http://stackoverflow.com/questions/3226390/sql-insert-system-date-into-table – ControlAltDel

回答

4

您應該使用PreparedStatement並通過日期字段廣告Date ...

String SQLString = "INSERT INTO Position (Date1) VALUES (?)"; 
PreparedStatement prest = con.prepareStatement(SQLString); 
prest.setDate(1,new Date()); 
prest.executeUpdate() 
+0

謝謝您的答覆。但我必須使用Statement.executeUpdate(),所以任何人都可以告訴我如何正確嵌入日期時間到SQL字符串? – newman

+0

什麼是SQL版本?應該使用:YYYY-MM-dd HH:mm:ss或不帶時間只需:YYYY-MM-dd或YYYYMMdd – aleroot

2

首先,你必須使用PreparedStatement。然後,你可以這樣做:

statement.setDate(2, new Date()); 
+0

謝謝您的回覆。但我必須使用Statement.executeUpdate(),所以任何人都可以告訴我如何正確嵌入日期時間到SQL字符串? – newman