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

Solution 1:

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:

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