Retrieve column names from java.sql.ResultSet
You can get this info from the ResultSet
metadata. See ResultSetMetaData
e.g.
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
String name = rsmd.getColumnName(1);
and you can get the column name from there. If you do
select x as y from table
then rsmd.getColumnLabel()
will get you the retrieved label name too.
In addition to the above answers, if you're working with a dynamic query and you want the column names but do not know how many columns there are, you can use the ResultSetMetaData object to get the number of columns first and then cycle through them.
Amending Brian's code:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}