如何在java中的结果集中迭代行的值?

Jas*_*ell 14 java sql jsp

结果集我说的是:http: //docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSet.html

我想做的是......

for row in rows
    for col in row
        //col is the name of the column, row[col] is the value.
Run Code Online (Sandbox Code Playgroud)

我在PHP中比JSP,fyi更有资格.这将在PHP中完成,如下所示:

foreach($rs as $row)
    foreach($row as $col => $val)
        //val is the cell value, and column is the column name
Run Code Online (Sandbox Code Playgroud)

编辑:我正在寻找一个通用的解决方案.注意col是一个变量,而不是一个文字.

DwB*_*DwB 20

这只是a_horse_with_no_name答案的变体.在这里我们使用那里建议ListList对象.

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 (final int column = 1; column <= columnCount; ++column) 
    {
        final Object value = rs.getObject(column);
        columnList.add(String.valueOf(value));
    }
}

// add the rowList to the request.
Run Code Online (Sandbox Code Playgroud)

编辑为所有变量添加了final.


a_h*_*ame 14

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我不建议直接在JSP页面中做这样的事情.在后端构建某种价值持有者(例如列表清单)并对其进行迭代.