Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"?

like image 204
Ken Chan Avatar asked Aug 30 '10 11:08

Ken Chan


People also ask

How do I get a list of column names in ResultSet?

You can get the name of a particular column using the getColumnName() method of the ResultSetMetadata interface. This method accepts an integer value representing the index of a column and returns a String value representing the name of the specified column.

How do you find the information about columns in a ResultSet object?

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.

How do you know if ResultSet contains data?

The JDBC ResultSet doesn't provide any isEmpty(), length() or size() method to check if its empty or not. Hence, when a Java programmer needs to determine if ResultSet is empty or not, it just calls the next() method and if next() returns false it means ResultSet is empty.

How do I know if a ResultSet column is null?

The wasNull() method of the ResultSet interface determines whether the last column read had a Null value. i.e. whenever you read the contents of a column of the ResultSet using the getter methods (getInt(), getString etc...) you can determine whether it (column) contains null values, using the wasNull() method.


1 Answers

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.

like image 79
Erick Robertson Avatar answered Sep 19 '22 18:09

Erick Robertson