Oracle JDBC驱动中对Date支持的改动

——一直我们在Oracle8i上面用的程序,昨天发现放到9i数据库上面,用9i的JDBC驱动
连接后,发现我们用Java的Date类型放入到数据库DATE类型字段的数据,没有了时分
秒的信息。但是在8i上面用8i的JDBC驱动是没有问题的。换了一个我们自己Patch过的
8iJDBC驱动连9i数据库,DATE型的数据又可以保存时间信息了。结论就是9i的驱动是
不能将Java的Date里面的时间信息放入到DATE里面。

——翻查了Oracle的FAQ,果然发现这个结论和相应的解决办法:

Prior to 9.2, the Oracle JDBC drivers mapped the DATE SQL type to java.sql.Timestamp. This made a certain amount of sense because the Oracle DATE SQL type contains both date and time information as does java.sql.Timestamp. The more obvious mapping to java.sql.Date was somewhat problematic as java.sql.Date does not include time information. It was also the case that the RDBMS did not support the TIMESTAMP SQL type, so there was no problem with mapping DATE to Timestamp.

In 9.2 TIMESTAMP support was added to the RDBMS. The difference between DATE and TIMESTAMP is that TIMESTAMP includes nanoseconds and DATE does not. So, beginning in 9.2, DATE is mapped to Date and TIMESTAMP is mapped to Timestamp. Unfortunately if you were relying on DATE values to contain time information, there is a problem.

There are several ways to address this problem:

Alter your tables to use TIMESTAMP instead of DATE. This is probably rarely possible, but it is the best solution when it is.

Alter your application to use defineColumnType to define the columns as TIMESTAMP rather than DATE. There are problems with this because you really don’t want to use defineColumnType unless you have to (see What is defineColumnType and when should I use it?).

Alter you application to use getTimestamp rather than getObject. This is a good solution when possible, however many applications contain generic code that relies on getObject, so it isn’t always possible.

Set the V8Compatibility connection property. This tells the JDBC drivers to use the old mapping rather than the new one. You can set this flag either as a connection property or a system property. You set the connection property by adding it to the java.util.Properties object passed to DriverManager.getConnection or to OracleDataSource.setConnectionProperties. You set the system property by including a -D option in your java command line.

java -Doracle.jdbc.V8Compatibility=”true” MyApp

《Oracle JDBC驱动中对Date支持的改动》上有1条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注