Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ResultSet - get Column name based on Index [duplicate]

Tags:

I want to know if there is a way to get a column name based on the index from a resultSet.

I know that if you want to get index based on the columnName, you can do that by using

int index = resultSet.findColumn(columnName);

But I need the other way around, something like :

String column = resultSet.findColumnName(index);

Is it possible?

like image 818
Rudy Avatar asked Jun 20 '11 09:06

Rudy


2 Answers

I think you need to look at ResultSet.getMetaData() which returns the meta-data associated with a ResultSet.

You can then iterate over the columns (use getColumnCount() to find out how many there are) to find the column with the given name, checking with getColumnName(). Don't forget that column indexes are 1-based, rather than 0-based. Something like:

ResultSetMetaData metaData = resultSet.getMetaData();

int count = metaData.getColumnCount();
for (int i = 1; i <= count; i++)
{
    if (metaData.getColumnName(i).equals(desiredColumnName))
    {
        // Whatever you want to do here.
    }
}

If you need to do this for a lot of names, you may want to build a HashMap<String, Integer> to map them easily.

like image 133
Jon Skeet Avatar answered Sep 21 '22 09:09

Jon Skeet


Of course - use java.sql.ResultSetMetaData.

ResultSetMetaData meta = resultSet.getMetaData();
String column = meta.getColumnName(index);
like image 7
duffymo Avatar answered Sep 20 '22 09:09

duffymo