如何确定 ResultSet 中是否存在列名?

由于 ResultSet包含从动态 SQL 返回的数据,是否有任何方法来确定 ResultSet是否包含特定的列名?

例如,如果我运行 rs.getString("Column_ABC")"Column_ABC"并不真正存在,它将抛出异常。

如何测试 ResultSet是否可以从名为 "Column_ABC"的列获得数据?

85197 次浏览

if not rs.getString("Column_ABC")= nothing then ' your code here

Use the ResultSetMetaData class.

public static boolean hasColumn(ResultSet rs, String columnName) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int columns = rsmd.getColumnCount();
for (int x = 1; x <= columns; x++) {
if (columnName.equals(rsmd.getColumnName(x))) {
return true;
}
}
return false;
}

The thing I don't understand is why this function would ever be needed. The query or stored procedure being executed should have known results. The columns of the query should be known. Needing a function like this may be a sign that there is a design problem somewhere.

Not sure if this is more or less efficient than Erick's answer but it's easier.

String str;


try {
str = rs.getString(columnName);
} catch (java.sql.SQLException e) {
str = null;
}
/**
* returns default value if column is not present in resultset
*
* @param rs
* @param columnLabel
* @param defaultValue
* @return
*/
@SuppressWarnings("unchecked")
private static <T> T getValueFromResultSet(final ResultSet rs,
String columnLabel, T defaultValue) {
try {
return (T) rs.getObject(columnLabel);
} catch (SQLException e) {
return defaultValue;
}
}

In java version >=7 you have a option of passing Class type in ResultSet#getObject method

private boolean isThere(ResultSet rs, String column){
try{
rs.findColumn(column);
return true;
} catch (SQLException sqlex){
logger.debug("column doesn't exist {}", column);
}


return false;
}

resultSet.getColumnMetaData().contains(columnName)