Sophie McCarrell
Sophie McCarrell

Reputation: 2871

How do I iterate through the values of a row from a result set in java?

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.

Upvotes: 16

Views: 68820

Answers (4)

DwB
DwB

Reputation: 38290

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.

Upvotes: 22

user330315
user330315

Reputation:

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.

Upvotes: 15

duffymo
duffymo

Reputation: 308743

It's easy if you use the Java Standard Tag Library.

Check this out, too:

http://docs.oracle.com/javaee/1.4/tutorial/doc/JSTL3.html

I would strongly discourage you from embedding scriptlet code in your JSPs. It's not the way to go.

If you accept that, then every other answer given here has to be discarded. They all belong in server-side Java classes, not a JSP.

Upvotes: 1

adarshr
adarshr

Reputation: 62573

Be sure to read through The Tutorial first.

while(rs.next()) {
    String col1 = rs.getString("NAME"); // if NAME is VARCHAR2, for eg.
}

While it is perfectly possible to read resultsets in JSP, that's not the right way to do it in Java. Such things should always be performed in a separate Java class whose result will be merely iterated in the JSP.

Upvotes: 0

Related Questions