2

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
  • 1
    See http://stackoverflow.com/questions/696782/retrieve-column-names-from-java-sql-resultset – Jayan Sep 03 '15 at 16:04
  • Of course, you do know that you shouldn't use `SELECT *` in queries in code, right? So your code that created the `ResultSet` would know if it queried the column in question. See [What is the reason not to use select *?](http://stackoverflow.com/questions/321299/what-is-the-reason-not-to-use-select) – Andreas Sep 03 '15 at 16:08
  • @Andreas I don't see a select * anywhere, even old version of question. I can be exceedingly dense, please forgive. – Drew Sep 03 '15 at 16:11
  • @Drew You don't see it because the code that produces the `ResultSet` is not posted in the question. That code *may* very well do a `SELECT *`. – Andreas Sep 03 '15 at 16:13
  • so I don't get why the `you know that you shouldn't use` part. You jumping to conclusions bro? Even if he did, do a select *, huh ? @Andreas, how does that even remotely help him ... idk – Drew Sep 03 '15 at 16:15
  • @Andreas: Thanks for this comment. No, I don't use SELECT *. I have two SELECT and use the same function parseResultSet for both of them – Klausos Klausos Sep 03 '15 at 16:17
  • Mureinik is our on call mysql master at the moment. Follow those that have tag rank – Drew Sep 03 '15 at 16:18
  • @KlausosKlausos Instead of having to scan the result columns using `getMetaData()`, I'd suggest that you pass a parameter to `parseResultSet` to let it know whether it's parsing column set 1 or column set 2, e.g. a `boolean hasDateTimeCheck` or whatever name fits your more complex scenario. – Andreas Sep 03 '15 at 16:29
  • @Andreas: Ok, thanks. – Klausos Klausos Sep 03 '15 at 16:52

1 Answers1

3

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;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350