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?
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.
Of course - use java.sql.ResultSetMetaData.
ResultSetMetaData meta = resultSet.getMetaData();
String column = meta.getColumnName(index);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With