SQL Server的timestamp2应该如何在JDBC中运行?

我在SQL Server 2008中尝试使用timestamp2而不是Timestamp时遇到了一些麻烦。显然,rs.getTimestamp在timestamp和timestamp2之间的行为非常不同。 但是,我找不到任何文件说明应该存在差异,或者我应该使用不同的东西。 我想知道我是否只是做错了什么。

环境:

  • 试用SQL Express 2008(10.0)和SQL Server 2008 R2(10.5)。
  • sqljdbc4.jar 3.0版,大小为537,303字节,CRC-32 = a0aa1e25,MD5 = 402130141d5f2cee727f4371e2e8fd8a。
  • Java 1.6

这是一个演示问题的unit testing。 唯一的“魔法”是“Db.getConnection()”,您可以使用适当的代码替换它。 datetime和datetime2的测试相同,但datetime2测试失败,日期为2天。 我将数据库中的所有时间视为GMT / UTC,并且我没有尝试将时区信息添加到datetime2数据的数据库数据中。

private void testTimestamp(TimeZone gmtTz, Connection conn, String query, Calendar expectedCal) throws SQLException { PreparedStatement stmt = conn.prepareStatement(query); ResultSet rs = stmt.executeQuery(); while (rs.next()) { // Note the expectedCal has a GMT timezone. Date actualTs = rs.getTimestamp("dt", expectedCal); // Just print out the time difference long diff = actualTs.getTime() - expectedCal.getTimeInMillis(); System.out.println("Diff=" + diff); // Do the test to make sure they are the same // In practice, this succeeds for datetime and fails for datetime2 Assert.assertEquals(expectedCal.getTimeInMillis(), actualTs.getTime()); } } @Test public void testDateTime() throws SQLException { Connection conn = Db.getConnection(); TimeZone gmtTz = TimeZone.getTimeZone("GMT"); String query; Calendar expectedCal = Calendar.getInstance(gmtTz); expectedCal.clear(); expectedCal.set(2011, 10, 02, 11, 17); query = "select CAST('2011-11-02 11:17:00' as datetime) as dt"; testTimestamp(gmtTz, conn, query, expectedCal); query = "select CAST('2011-11-02 11:17:00.0000000' as datetime2) as dt"; testTimestamp(gmtTz, conn, query, expectedCal); // results in an error } 

我唯一的选择是切换回时间戳吗?

编辑:对于未来的Google员工,使用sqljdbc4.jar 3.0版,测试在Linux上失败,但在Windows上传递。 我还没有尝试过SQL Server 2012附带的sqljdbc4.jar 4.0版。

我记得没有听到关于官方SQL Server驱动程序和JTDS的优点(尽管我似乎无法找到该链接)。 我个人会选择JTDS(当然要经过严格的测试)或者回到不会引起问题的版本。 我没有使用SQL Server,但从外观来看,似乎datetime2是首选的数据类型,所以我宁愿不回复。 选项(d)不是IMO的好选择。 🙂

如果您将Sun JRE 1.7与Microsoft JDBC 3.0驱动程序一起使用,请参阅此博客文章http://blogs.msdn.com/b/jdbcteam/archive/2012/01/20/hotfix-available-for-date-issue-when -using-jre-1-7.aspx 。

如果您发现我们的驱动程序中发现了错误,您可以通过Microsoft Connect报告。 https://connect.microsoft.com/SQLServer