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"
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With