Having rs
, an instance of java.sql.ResultSet, how to check that it contains a column named "theColumn"?
You can use ResultSetMetaData. getColumnLabel if you are interested in getting the name as defined by the AS clause of your SQL query.
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.
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.
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.
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!"); } }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With