欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PrepareStatement插入时间 JavaSQLJDK 

程序员文章站 2024-02-20 22:03:36
...
java.sql.Date stores only date information, not times. Simply converting a java.util.Date into a java.sql.Date will silently set the time to midnight. So, to store date/times to be manipulated as java.util.Date objects, don’t do this:

// BUG: loses time of day
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));

do this instead:

preparedStatement.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
java.sql.Timestamp is not a date

java.sql.Timestamp extends java.util.Date, but it should not be used as a Date. In JDK 1.3.1, Timestamp.getTime() (inherited from Date) returns the time to the nearest second only, but JDK 1.4.2 and JDK 1.5 it returns the time to the nearest millisecond as expected. So in JDK 1.3, when reading a timestamp from a ResultSet, don’t do this:

// Java 1.3
java.util.Date d = resultSet.getTimestamp(1);
long millis = d.getTime(); // BUG: loses fractional seconds in JDK 1.3

To get the full date including milliseconds, you have to do this:

java.sql.Timestamp timestamp = resultSet.getTimestamp(1);
java.util.Date d = new java.util.Date(timestamp.getTime() +
                                      timestamp.getNanos() / 1000000);

In JDK 1.4.2 and JDK 1.5, you can just do this, depending on what you’re going to do with the Date:

// Java 1.4+
java.util.Date d = resultSet.getTimestamp(1);

But this might be safer since it avoids any other potential Timestamp problems:

// Java 1.4+
java.util.Date d = new java.util.Date(resultSet.getTimestamp(1).getTime());

If your code needs to run on JDK 1.3 and later, you’ll have to do this:

java.sql.Timestamp timestamp = resultSet.getTimestamp(1);
long millis = (timestamp.getTime() / 1000) * 1000 + timestamp.getNanos() / 1000000;
java.util.Date d = new java.util.Date(millis);


http://www.thunderguy.com/semicolon/2003/08/14/java-sql-date-is-not-a-real-date/
相关标签: Java SQL JDK