How can I determine if the column name exist in the ResultSet?

JavaJdbcResultset

Java Problem Overview


As the ResultSet contains the data returned from the dynamic SQL, if there are any method to determine if the ResultSet contains a particular column name?

For example , if I run rs.getString("Column_ABC") but "Column_ABC" does not really exist, it will throw out the exception.

How can I test if the ResultSet can get a data from a column named "Column_ABC"?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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;
}

Solution 3 - Java

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;
}

Solution 4 - Java

resultSet.getColumnMetaData().contains(columnName)

Solution 5 - Java

/**
 * 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

Solution 6 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKen ChanView Question on Stackoverflow
Solution 1 - JavaErick RobertsonView Answer on Stackoverflow
Solution 2 - JavaTalickView Answer on Stackoverflow
Solution 3 - JavaZip184View Answer on Stackoverflow
Solution 4 - Javasanket patwardhanView Answer on Stackoverflow
Solution 5 - JavaVivekJView Answer on Stackoverflow
Solution 6 - JavaAmitView Answer on Stackoverflow