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

2020-04-03 04:44发布

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.

7条回答
The star\"
2楼-- · 2020-04-03 05:15

Following on from the top answer in this thread from Jared, and one of its under-rated comments from corsiKa:

ResultSetMetaData meta = crs.getMetaData();
int numCol = meta.getColumnCount();
Set<String> columns = new HashSet<>;

for (int i = 1; i <= numCol; i++) 
{
    columns.add(meta.getColumnName(i));    
}


return columns.contains("name");
查看更多
登录 后发表回答