在 jTDS 中使用 datetimeoffset 数据类型

Ami*_*iya 6 sql-server jtds jdbc datetimeoffset sql-server-2008

jTDS 当前不支持datetimeoffsetSQL Server 2008 中引入的数据类型。

任何人都可以建议是否有办法将datetimeoffset类型与 jTDS一起使用?

Gor*_*son 4

正如datetimeoffset 文档的“下级客户端的向后兼容性”部分中提到的,我们可以使用datetimeoffset值的字符串表示形式。事实上,如果我们datetimeoffset使用 jTDS 1.3.1 检索一个值,我们会得到以下java.lang.String形式的值

YYYY-MM-DD hh:mm:ss[.nnnnnnn] {+|-}hh:mm
Run Code Online (Sandbox Code Playgroud)

这样的值可以这样解析:

// rs is our ResultSet object
String valueRetrieved = rs.getString(1);  // e.g., "2016-12-08 12:34:56.7850000 -07:00"
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS ZZZZZ");
ZonedDateTime zdt = ZonedDateTime.parse(valueRetrieved, dtf);
Run Code Online (Sandbox Code Playgroud)

至于datetimeoffset向 SQL Server 写入值,jTDS 无法正确处理更新.setTimestamp,例如在我的机器上...

java.sql.Timestamp ts = java.sql.Timestamp.valueOf("2016-12-08 12:34:56.785");  // local
String tsString = formatTimestampForDateTimeOffset(ts);  // (see below)
System.out.printf("             java.sql.TimeStamp value: %s (%d ms since epoch)%n", tsString, ts.getTime());

System.out.println();
System.out.println("Saving via setTimestamp ...");
String sqlUpdate = "UPDATE dtoTable SET dtoCol = ? WHERE id=1";
try (PreparedStatement s = conn.prepareStatement(sqlUpdate)) {
    s.setTimestamp(1, ts);  // pass the Timestamp itself
    s.executeUpdate();
}
String valueRetrieved;
try (
        Statement s = conn.createStatement();
        ResultSet rs = s.executeQuery("SELECT dtoCol FROM dtoTable WHERE id=1")) {
    rs.next();
    valueRetrieved = rs.getString(1);
    System.out.printf("    jTDS saved the TimeStamp value as: %s%n", valueRetrieved);
}
Run Code Online (Sandbox Code Playgroud)

...产生...

         java.sql.TimeStamp value: 2016-12-08 12:34:56.785 -07:00 (1481225696785 ms since epoch)

Saving via setTimestamp ...
jTDS saved the TimeStamp value as: 2016-12-08 12:34:56.7870000 +00:00
Run Code Online (Sandbox Code Playgroud)

...这不仅错误地将时区偏移设置为 +00:00(不更改日期/时间值本身),而且还增加了几毫秒只是为了好玩。

但是,如果我们将时间戳值转换为格式正确的字符串,例如...

public static String formatTimestampForDateTimeOffset(java.sql.Timestamp ts) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS ZZZZZ");
    String s = sdf.format(new Date(ts.getTime()));
    // T-SQL *requires* the colon in the timezone offset: -07:00, not -0700
    int colonPosition = s.length() - 2;
    return s.substring(0, colonPosition) + ":" + s.substring(colonPosition);
}
Run Code Online (Sandbox Code Playgroud)

...并使用.setString而不是.setTimestamp,则该datetimeoffset值被正确保存:

Saving via setString ...
jTDS saved the formatted String as: 2016-12-08 12:34:56.7850000 -07:00
           parsed to ZonedDateTime: 2016-12-08T12:34:56.785-07:00
              converted to Instant: 2016-12-08T19:34:56.785Z
       converted to java.util.Date: Thu Dec 08 12:34:56 MST 2016
Run Code Online (Sandbox Code Playgroud)