Java 要列出的结果集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1966836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:53:29  来源:igfitidea点击:

Resultset To List

javajspjdbc

提问by Gnaniyar Zubair

I want to convert my Resultset to List in my JSP page. and want to display all the values. This is my query:

我想在我的 JSP 页面中将我的结果集转换为列表。并希望显示所有值。这是我的查询:

SELECT userId, userName 
  FROM user;

I have executed that using preparedstatementand got the Resultset. But how to convert it as a Listand want to display the result like this:

我已经执行,使用PreparedStatement的,并得到了结果集。但是如何将其转换为List并希望像这样显示结果:

userID  userName
------------------
1001    user-X 
1006    user-Y  
1007    user-Z

采纳答案by OMG Ponies

You need to iterate over the ResultSetobject in a loop, row by row, to pull out each column value:

您需要在循环中逐行迭代ResultSet对象,以提取每个列值:

List ll = new LinkedList();
ResultSet rs = stmt.executeQuery("SELECT userid, username FROM USER");

// Fetch each row from the result set
while (rs.next()) {
  int i = rs.getInt("userid");
  String str = rs.getString("username");

  //Assuming you have a user object
  User user = new User(i, str);

  ll.add(user);
}

回答by Brian Agnew

You could always use Commons DbUtilsand the MapListHandler. From the doc:

您始终可以使用Commons DbUtilsMapListHandler。从文档:

ResultSetHandler implementation that converts a ResultSet into a List of Maps

将 ResultSet 转换为 Maps 列表的 ResultSetHandler 实现

so it'll take a lot of boilerplate code out of your hands.

所以它会从你手中拿走很多样板代码。

回答by duffymo

A ResultSet should never get as far as a JSP. It should be mapping into a data structure or object and closed inside the method scope in which it was created. It's a database cursor, a scarce resource. Your app will run out of them soon if you persist with such a design.

ResultSet 永远不会像 JSP 那样深入。它应该映射到数据结构或对象中,并在创建它的方法范围内关闭。它是一个数据库游标,一种稀缺资源。如果您坚持这样的设计,您的应用程序很快就会耗尽它们。