With java.sql.ResultSet
is there a way to get a column's name as a String
by using the column's index? I had a look through the API doc but I can't find anything.
views:
1530answers:
3
+16
A:
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.
Brian Agnew
2009-03-30 11:13:12
Perfect, that's exactly what I needed :)
2009-03-30 11:18:48
A:
I can't create comments yet, so posting this as an answer.
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.
Ammending 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 + 1; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
Cyntech
2010-09-29 04:24:35