javajdbcmetadatacachedrowset

How do I check to see if a column name exists in a CachedRowSet?


I am querying data from views that are subject to change. I need to know if the column exists before I do a crs.get******().

I have found that I can query the metadata like this to see if a column exist before I request the data from it:

ResultSetMetaData meta = crs.getMetaData();
int numCol = meta.getColumnCount();

for (int i = 1; i < numCol + 1; i++) 
    if (meta.getColumnName(i).equals("name"))
        return true;

Is there a simpler way of checking to see if a column exists?


EDIT

It must be database agnostic. That is why I am referencing the CachedRowSet instead of the database.


Solution

  • There's not a simpler way with the general JDBC API (at least not that I know of, or can find...I've got exactly the same code in my home-grown toolset.)

    Your code isn't complete:

    ResultSetMetaData meta = crs.getMetaData();
    int numCol = meta.getColumnCount();
    
    for (int i = 1; i < numCol + 1; i++) {
        if (meta.getColumnName(i).equals("name")) {
            return true;
        }
    }
    
    return false;
    

    That being said, if you use proprietary, database-specific API's and/or SQL queries, I'm sure you can find more elegant ways of doing the same thing. Bbut you'd have to write custom code for each database you need to deal with. I'd stick with the JDBC APIs, if I were you.

    Is there something about your proposed solution that makes you think it's incorrect? It seems simple enough to me.