Having rs
, an instance of java.sql.ResultSet, how to check that it contains a column named "theColumn"?
views:
67answers:
4
+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ć
2010-10-15 13:23:08
Aren't exceptions slow?
Ivan
2010-10-15 14:01:44
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ć
2010-10-15 14:47:42
+2
A:
You can do:
rs.findColumn("theColum")
and check for SQLException
Alois Cochard
2010-10-15 13:24:40
Yeah, easiest way I would think is to just try to retrieve the column one way or another and catch the exception.
Jay
2010-10-15 15:51:39
+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
2010-10-15 13:28:23
@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
2010-10-15 23:17:46
A:
Use the ResultSetMetaData object provided by the ResultSet object via rs.getMetaData()
darri
2010-10-15 13:29:29