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

结果集我说的是: 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是一个变量,而不是文字。

这只是a_horse_with_no_name答案的变体。 这里我们使用ListList对象。

 final ResultSetMetaData meta = rs.getMetaData(); final int columnCount = meta.getColumnCount(); final List> rowList = new LinkedList>(); while (rs.next()) { final List columnList = new LinkedList(); 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. 

编辑为所有变量添加最终。

 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页面中做这样的事情。 在后端构建某种价值持有者(例如列表清单)并对其进行迭代。

如果您使用Java标准标记库,这很容易。

检查一下:

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

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

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

请务必先阅读“教程” 。

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

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