将oracle.sql.timestamptz转换为java.sql.Timestamp

时间:2011-12-01 09:30:35

标签: java sql oracle

我正在尝试将(Oracle)数据库的systimestamp转换为java.sql.Timestamp

(部分)我测试过程的代码是:

try {
    conn = this.getConnection();
    Statement stmt = conn.createStatement();

    stmt.execute("SELECT SYSTIMESTAMP FROM DUAL");

    ResultSet rs = stmt.getResultSet();
    ResultSetMetaData rsm = rs.getMetaData();

    while(rs.next()) {
        TIMESTAMPTZ ts = (TIMESTAMPTZ) rs.getObject(1);
        System.out.println(ts);
        System.out.println(ts.getClass());
        System.out.println(ts.timestampValue());
    }
} catch (SQLException e) {
    e.printStackTrace();
    System.out.println(e);
}

我得到的输出是:

oracle.sql.TIMESTAMPTZ@1e97f9f
class oracle.sql.TIMESTAMPTZ

and then an exception:
java.sql.SQLException: Conversion to Timestamp failed
at oracle.sql.Datum.timestampValue(Datum.java:283)
at com.sumawest.test.model.UnitTest.testTimezone(UnitTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at oracle.jdevimpl.junit.runner.TestRunner.doRun(TestRunner.java:111)
at oracle.jdevimpl.junit.runner.TestRunner.start(TestRunner.java:91)
at oracle.jdevimpl.junit.runner.TestRunner.main(TestRunner.java:43)
java.sql.SQLException: Conversion to Timestamp failed

有谁知道如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

如果您对代码进行反编译,则可以看到您正在调用父timestampValue类的Datum方法。

这会直接抛出异常(方法中没有其他代码)。您需要调用timestampValue TIMESTAMPTZ方法,并传递Connection

答案 1 :(得分:0)

您可以使用to_char函数将其转换为字符串,然后使用该值。

select to_char(systimestamp, 'IYYY-MM-DD HH24:MI:SS.FF TZD') as d from dual;