Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

sql - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...