How to check that a ResultSet contains a specifically named field?

Ivan picture Ivan · Oct 15, 2010 · Viewed 38k times · Source

Having rs, an instance of java.sql.ResultSet, how to check that it contains a column named "theColumn"?

Answer

Buhake Sindi picture Buhake Sindi · Oct 15, 2010

You can use ResultSetMetaData to iterate through the ResultSet columns and see if the column name matches your specified column name.

Example:

ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();

// get the column names; column indexes start from 1
for (int i = 1; i < numberOfColumns + 1; i++) {
    String columnName = rsMetaData.getColumnName(i);
    // Get the name of the column's table name
    if ("theColumn".equals(columnName)) {
        System.out.println("Bingo!");
    }
}