Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 678
Ivan Avatar asked Oct 15 '10 13:10

Ivan


People also ask

How can I determine if the column name exist in the ResultSet?

You can use ResultSetMetaData. getColumnLabel if you are interested in getting the name as defined by the AS clause of your SQL query.

How do you know if ResultSet contains data?

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.

How do I get a specific row in ResultSet?

The getRow() method of the ResultSet interface retrieves the current row number/position of the ResultSet pointer. This method returns an integer value representing the current row number to which the ResultSet pointer points to.

What is ResultSet getString ()?

getString(String columnLabel) Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. Time. getTime(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a java.


2 Answers

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!");     } } 
like image 84
Buhake Sindi Avatar answered Sep 21 '22 02:09

Buhake Sindi


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; } 
like image 32
Boris Pavlović Avatar answered Sep 22 '22 02:09

Boris Pavlović