java.lang.ClassCastException: oracle.sql.TIMESTAMP 不能转换为 java.sql.Timestamp
我正在开发一个通过网络流式传输 ResultSet 的应用程序.我最终使用了 CachedRowSetImpl 类.但是当我连接到 Oracle DB 时,出现这样的错误
I am working on an application that streams ResultSet over a network. I ended up using a CachedRowSetImpl class. But when I connect to an Oracle DB, I get an error like this
java.lang.ClassCastException: oracle.sql.TIMESTAMP 无法转换为 java.sql.Timestamp
java.lang.ClassCastException: oracle.sql.TIMESTAMP cannot be cast to java.sql.Timestamp
请帮忙.
源码如下:
ResultSet res = response.getResultSet(); //resultset from the server
while (res.next()) {
Agent agent = new Agent();
agent.setName(res.getString(2));
agent.setMobile(res.getString(1));
agent.setBalance(res.getLong(4));
agent.setLastUpdate(res.getDate(3)); //date from the result set
agent.setAccountNumber(res.getString(5));
}
错误...
java.lang.ClassCastException: oracle.sql.TIMESTAMP 不能转换为 java.sql.Timestampjava.lang.ClassCastException: oracle.sql.TIMESTAMP 不能转换为 java.sql.Timestamp在 com.sun.rowset.CachedRowSetImpl.getDate(CachedRowSetImpl.java:2139)
java.lang.ClassCastException: oracle.sql.TIMESTAMP cannot be cast to java.sql.Timestamp java.lang.ClassCastException: oracle.sql.TIMESTAMP cannot be cast to java.sql.Timestamp at com.sun.rowset.CachedRowSetImpl.getDate(CachedRowSetImpl.java:2139)
推荐答案
ResultSet.getObject() 要求 JDBC 类型应映射到 JDBC 规范 (TIMESTAMP -> java.sqlTimestmp) 规定的 Java 类型:
The javadoc for ResultSet.getObject() mandates that the JDBC type should be mapped to a Java type as prescribed by the JDBC spec (TIMESTAMP -> java.sqlTimestmp):
此方法将返回给定列的值作为 Java目的.Java 对象的类型将是默认的 Java 对象对应于列的 SQL 类型的类型,遵循以下映射JDBC 规范中指定的内置类型.
This method will return the value of the given column as a Java object. The type of the Java object will be the default Java object type corresponding to the column's SQL type, following the mapping for built-in types specified in the JDBC specification.
如您所见,Oracle 驱动程序默认不符合标准,而是使用 oracle.sql.TIMESTAMP
(不扩展 java.sql.时间戳
).好消息是,您可以通过在 vm 启动期间将 oracle.jdbc.J2EE13Compliant 系统属性设置为 true
来强制遵守 JDBC:
As you have noticed, the Oracle driver is by default not compliant with the standard and uses oracle.sql.TIMESTAMP
instead (which does not extend java.sql.Timestamp
). The good news is that you can force JDBC compliance by setting the oracle.jdbc.J2EE13Compliant system property to true
during vm startup:
java -Doracle.jdbc.J2EE13Compliant=true YourApplication
或以编程方式
System.getProperties().setProperty("oracle.jdbc.J2EE13Compliant", "true")
执行此操作后,getResult() 将按预期返回 java.sql.Timestamp
的实例.
Once you do this, getResult() will return instances of java.sql.Timestamp
, as expected.
有关更多详细信息,请参阅Oracle JDBC 驱动程序文档中的相关部分a>,描述了oracle.jdbc.J2EE13Compliant的几种设置方式.
For more details see the relevant section from the Oracle JDBC Driver Documentation, which describes several ways of setting oracle.jdbc.J2EE13Compliant.
相关文章