The result set I'm speaking of this: http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSet.html
What I would like to do is this...
for row in rows
for col in row
//col is the name of the column, row[col] is the value.
I'm more profecient in PHP, than JSP, fyi. This would be done in PHP like so:
foreach($rs as $row)
foreach($row as $col => $val)
//val is the cell value, and column is the column name
EDIT: I'm looking for a generic solution. notice how col is a variable, not a literal.
To iterate the ResultSet you use its next() method. The next() method returns true if the ResultSet has a next record, and moves the ResultSet to point to the next record. If there were no more records, next() returns false, and you can no longer.
You can use absolute to navigate to the first row: ResultSet rs = ...; rs. absolute(1); // Navigate to first row int id = rs.
You can move the cursor of the ResultSet object to the next row from the current position, using the next() method of the ResultSet interface. This method returns a boolean value specifying whether the ResultSet object contains more rows.
The ResultSet interface declares getter methods (for example, getBoolean and getLong ) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column.
This is just a variation the a_horse_with_no_name answer.
Here we use a List
of List
objects as suggested there.
final ResultSetMetaData meta = rs.getMetaData();
final int columnCount = meta.getColumnCount();
final List<List<String>> rowList = new LinkedList<List<String>>();
while (rs.next())
{
final List<String> columnList = new LinkedList<String>();
rowList.add(columnList);
for (int column = 1; column <= columnCount; ++column)
{
final Object value = rs.getObject(column);
columnList.add(String.valueOf(value));
}
}
// add the rowList to the request.
Edit Added final to all variables.
ResultSetMetaData meta = rs.getMetaData();
int colCount = meta.getColumnCount();
while (rs.next())
{
for (int col=1; col <= colCount; col++)
{
Object value = rs.getObject(col);
if (value != null)
{
System.out.print(value.toString());
}
}
}
But I would not recommend to do something like this directly in the JSP page. Build up some kind of value holder (e.g. a List of Lists) in the backend and iterate over that.
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