Search code examples
javamysqlsqljdbcsqlexception

How to verify the existence of a column in table


I want to check if DateTimeCheck column exists before reading its value:

private void parseResultSet(ResultSet ride) {
  if (ride.getDate("DateTimeCheck") != null)
            this.RideDate = df.format(ride.getDate("DateTimeCheck"));

}

This code still provides this error:

java.sql.SQLException: Column 'DateTimeCheck' not found.

How to fix it?


Solution

  • You could use the ResultSetMetadata to check for the column's existence.

    private static boolean hasColumn (RestultSet rs, String column) {
        RestulSetMetaData md = rs.getMetaData();
        int colCount = md.getColumnCount();
        for (int i = 1; i <= colCount; ++i) { // Note that column indexes are 1-based
            if (column.equalsIgnoreCase(rs.getColumnName(i))) {
                return true;
            }
        }
        return false;
    }