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

问题描述 投票:13回答:4

结果集我说的是: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.

我更擅长PHP,然后是JSP,fyi。这将在PHP中完成,如下所示:

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

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

java sql jsp
4个回答
19
投票

这只是变化the a_horse_with_no_name answer。在这里,我们使用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.

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


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());
        }
    }
}

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


1
投票

如果你使用Java Standard Tag Library很容易。

检查一下:

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

我强烈建议您不要在JSP中嵌入scriptlet代码。这不是要走的路。

如果您接受,那么此处给出的每个其他答案都必须被丢弃。它们都属于服务器端Java类,而不是JSP。


0
投票

一定要先阅读The Tutorial

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

虽然完全可以在JSP中读取结果集,但这不是在Java中执行它的正确方法。这些事情应始终在一个单独的Java类中执行,其结果将仅在JSP中迭代。

© www.soinside.com 2019 - 2024. All rights reserved.