tags:

views:

54

answers:

3

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

A: 

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

Amit
This is a bad idea, and it's also wrong. When a column doesn't exist, it doesn't return nothing. It throws an SQLException, which you have to catch and handle. You should never use an exception being thrown for a simple check like this. You should always look for a method that would actually return a boolean - something that will actually perform a proper check.
Erick Robertson
+3  A: 
function boolean hasColumn(ResultSet rs, String columnName) {
  boolean hasColumn = false;
  ResultSetMetaData rsmd = rs.getMetaData();
  int columns = rsmd.getColumnCount();
  for (int x = 0; x < columns; x++) {
    if (columnName.equals(rsmd.getColumnName(x))) {
      hasColumn = true;
      break;
    }
  }
  return hasColumn;
}

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.

Erick Robertson
When executing user queries in tools like TOAD the application does not know the query structure and must use `ResultSetMetaData`. But yes, searching for a particular column name is strange.
gpeche
Just commenting... in your example, you're retrieving all column info. For a user query, I expect this to be standard. This is still not searching to see if a specific column is included.
Erick Robertson