Prefacejava
Environment:
Platform: Windows XP
Language: Java 1.5
IDE: MyEclipse 6.0.1
Database: SQL Server 2005 Enterprise ensql
Introductionspa
本文主要講述Java中的Date Time 與SQL Server 2005裏的Datetime 如何進行交互。涉及到的Date Type有
java.util.Date
java.sql.Date
java.sql.Time
java.sql.Timestamporm
Section 1 - java.util.Dateip
通過一些testing,大概瞭解了這幾個類的實際用法與限制。get
java.util.Date create 的instance 是不能直接讓JDBC 存到DB的,它會出現以下Exception:
Conversion failed when converting datetime from character string.string
要將java.util.Date存到DB必須通過 type conversion成爲sql下的Date,Time或Timestamp。io
Section 2 - java.sql.Dateform
java.sql.Date只能將date存到DB,time將被截取而由DB中最小的time值(00:00:00)所取代。test
Code:
java.util.Date currentDateTime = new java.util.Date();
System.out.println(currentDateTime);
System.out.println(currentDateTime.getTime());
Date currentDate = new Date(currentDateTime.getTime());
System.out.println(currentDate);
System.out.println(currentDate.getTime());
String strSQL = "insert into TestDateTime values('"+currentDate+"')";
executeHelper(strSQL);
Console Output:
Tue May 20 15:51:48 CST 2008
1211269908671
2008-05-20
1211269908671
Datebase Output:
2008-5-20 0:00:00
從result能夠看出java.sql.Date實際並非在其instance中就截取time,由於獲得的Long值仍然跟java.util.Date的Long值同樣,只是在顯示輸出或者對DB操做時才截去tIme的輸出。0:00:00是由DB其System的最小time補充的。
Section 3 - java.sql.Time
java.sql.Time只能講time存到DB,date將被截取而由DB中最小的date值(1900-1-1)所取代。
Code:
java.util.Date currentDateTime = new java.util.Date();
System.out.println(currentDateTime);
System.out.println(currentDateTime.getTime());
Time currentTime = new Time(currentDateTime.getTime());
System.out.println(currentTime);
System.out.println(currentTime.getTime());
String strSQL = "insert into TestDateTime values('"+currentTime+"')";
executeHelper(strSQL);
Console Output:
Tue May 20 16:03:52 CST 2008
1211270632312
16:03:52
1211270632312
Datebase Output:
1900-1-1 16:03:52
從result能夠看出java.sql.Time實際並非在其instance中就截取date,由於獲得的Long值仍然跟java.util.Date的Long值同樣,只是在顯示輸出或者對DB操做時才截去date的輸出。1900-1-1是由DB其System的最小date補充的。
Section 4 - java.sql.Timestamp
java.sql.Timestamp能夠將date和time都存到DB。
Code:
java.util.Date currentDateTime = new java.util.Date();
System.out.println(currentDateTime);
System.out.println(currentDateTime.getTime());
Timestamp currentTimestamp = new Timestamp(currentDateTime.getTime());
System.out.println(currentTimestamp);
System.out.println(currentTimestamp.getTime());
String strSQL = "insert into TestDateTime values('"+currentTimestamp+"')";
executeHelper(strSQL);
Console Output:
Tue May 20 16:24:40 CST 2008
1211271880796
2008-05-20 16:24:40.796
1211271880796
Datebase Output:
2008-5-20 16:24:40
從result能夠看出java.sql.Timestamp的存儲格式跟java.util.Date的不一樣,Timestamp的格式是專門對DB操做所定義的規範化格式,也就是說DB只能接收到這種格式傳過來的值,這也能夠大概知道爲何java.util.Date爲何不能直接傳值給DB了。