这似乎仍然是 jTDS 1.3.1 的一个未解决问题。我可以通过直接在 SQL Server 表目录中查询我正在使用的表并获取表的日期列列表来解决它:
private HashMap<String,Boolean> getDateColumns (String tableName, String schemaName, Connection conn) throws Exception {
String sql = "SELECT table_name + ',' + column_name"
+ " FROM INFORMATION_SCHEMA.COLUMNS "
+ " WHERE TABLE_SCHEMA = N'" + schemaName + "' "
+ " AND table_name = N'" + tableName + "' "
+ " AND data_type IN ('date', 'datetime', 'datetime2')";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
HashMap<String,Boolean> dateCols = new HashMap<String,Boolean>();
while (rs.next()) {
String tableColKey = rs.getString(1);
dateCols.put(tableColKey.toUpperCase(), true );
}
rs.close();
return dateCols;
}
获得此列表后,您可以显式检查该列是否为日期类型:
private ResultSetMetaData getTableMetaData (String tableName, Connection conn) throws Exception {
String sql = "SELECT * FROM dbo." + tableName + " where 1 = 2 ";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
rs.close();
HashMap<String,Boolean> dateColumns = getDateColumns (tableName, conn);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String key = tableName + "," + rsmd.getColumnName(i);
int type = -1;
if (dateColumns.containsKey(key)) {
type = Types.DATE;
}
else {
type = rsmd.getColumnType(i);
}
System.out.println ("... col: " + rsmd.getColumnName(i) + ", driver type name: " + rsmd.getColumnTypeName(i) + ", driver type: " + rsmd.getColumnType(i) + ", final data type: " + type);
}
return rsmd;
}
所以,假设我有一个包含三列的示例表:
SAMPLE
------------------
SITE_ID numeric
START_DATE date
END_DATE date
使用 jTDS 运行时,此代码将打印以下值:
... col: SITE_ID, driver type name: numeric, driver type: 2, final data type: 2
... col: START_DATE, driver type name: nvarchar, driver type: 12, final data type: 91
... col: END_DATE, driver type name: nvarchar, driver type: 12, final data type: 91
这并不理想,但它应该适用于其他有类似问题的人。