Java中的Date Time 与SQL Server 2005里的Datetime 之间的交互

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了。

相关文章
相关标签/搜索