日期:2014-05-16  浏览次数:20585 次

OJDBC版本不同引发的DATE问题

一般的数据库中,DATE字段仅仅表示日期,不包括日期信息,而Oracle数据库中的DATE数据类型是包括日期、时间的,对于不同的Oracle jdbc驱动版本,对于该问题的处理都有些区别,如果你使用9i或者11g
的驱动程序,可能不会发现什么困惑,不幸的话,你使用Oracle10g的JDBC驱动,问题就来了,你会发现时间不见了
看下面的程序
? 表结构如下

create table t_test(
id int,
date1 date,
date2 timestamp,
primary key(id)
)

??? 程序如下

public class JdbcTestDate {
	public static void executeJdbc(boolean onlyHuiPiao) throws SQLException {
		Connection conn = null;
		Statement ptmt = null;
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@10.1.252.80:1521:newngboss", "so1", "so1");
			System.out.println(conn.getMetaData().getDriverName() + " " + conn.getMetaData().getDriverVersion());
			ResultSet rs = conn.createStatement().executeQuery("select date1,date2 from t_test");
			rs.next();
			printInfo(rs, 1);
			printInfo(rs, 2);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ptmt != null)
				ptmt.close();
			if (conn != null)
				conn.close();
		}
	}

	public static void printInfo(ResultSet rs, int i) throws SQLException {
		ResultSetMetaData meta = rs.getMetaData();
		System.out.printf("Colname=%s,Type=%s,TypeName=%s,val=[%s];\n", meta.getColumnName(i), meta.getColumnType(i), meta
				.getColumnTypeName(i), rs.getObject(i).toString());
	}

	public static void main(String[] args) {
		try {
			executeJdbc(true);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

?

?? 如果使用9i或者11g的驱动连接数据库,返回结果如下:
9i数据库JDBC
oracle.jdbc.driver.OracleConnection@16930e2
Oracle JDBC driver 9.2.0.8.0
Colname=DATE1,Type=91,TypeName=DATE,val=[2008-06-13 13:48:21.0];
Colname=DATE2,Type=93,TypeName=TIMESTAMP,val=[oracle.sql.TIMESTAMP@18d107f];

11g数据库JDBC
oracle.jdbc.driver.T4CConnection@a61164
Oracle JDBC driver 11.1.0.6.0-Production+
Colname=DATE1,Type=93,TypeName=DATE,val=[2008-06-13 13:48:21.0];
Colname=DATE2,Type=93,TypeName=TIMESTAMP,val=[oracle.sql.TIMESTAMP@c4aad3];

如果使用10g JDBC驱动,结果如下:
oracle.jdbc.driver.T4CConnection@1bac748
Oracle JDBC driver 10.2.0.2.0
Colname=DATE1,Type=91,TypeName=DATE,val=[2008-06-13];
Colname=DATE2,Type=93,TypeName=TIMESTAMP,val=[oracle.sql.TIMESTAMP@b8df17];

结果是让人困惑,时间怎么不见了?

?

对于该问题,在Oracle的JDBC 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 TIME