views:

67

answers:

4

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

+1  A: 

Try using the method ResultSet#findColumn(String)

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;
}
Boris Pavlović
Aren't exceptions slow?
Ivan
It may be compared to a regular execution of Java. Bear in mind that usually bottleneck is not the Java code but the thins that are running on the other side -- the database. Most probably execution of the query and transport of data is few orders of magnitude slower than exception handling.
Boris Pavlović
+2  A: 

You can do:

rs.findColumn("theColum")

and check for SQLException

Alois Cochard
Yeah, easiest way I would think is to just try to retrieve the column one way or another and catch the exception.
Jay
+3  A: 

You can use ResultSetMetaData to iterate throw 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!");
    }
}
The Elite Gentleman
@Ivan, be aware there are some complexities if you use an alias (SELECT col AS foo). http://bugs.mysql.com/bug.php?id=43684
Joshua Martell
A: 

Use the ResultSetMetaData object provided by the ResultSet object via rs.getMetaData()

darri