如何在jsp中从javabean打印结果集数据?

时间:2012-02-20 02:29:56

标签: jsp javabeans

她是我的测试jsp代码和javabean db函数代码:

JSP:

<%

conn.init();
ResultSet rs = conn.selectProductById (request.getParameter("pid"));

while (rs.next()) {
    System.out.println(rs.getString("pid"));
}

}  

%>

的JavaBean:

public ResultSet selectProductById(String pid){

PreparedStatement pstmt = null;
ResultSet rs = null;
    try {
        String query = "select * from product where pid = ? ;";

        pstmt = connection.prepareStatement(query); // create a statement
        pstmt.setString(1, pid); // set input parameter
        System.out.println(pstmt);

        rs = pstmt.executeQuery();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            pstmt.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
     }
return rs;
}

错误:

type Exception report

message

descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: java.sql.SQLException: Operation not allowed after ResultSet closed
root cause

java.sql.SQLException: Operation not allowed after ResultSet closed
note The full stack traces of the exception and its root causes are available in the GlassFish Server 

jsp代码尝试从javabean的方法获取结果集但是有错误。如何解决?

感谢

2 个答案:

答案 0 :(得分:1)

您正在关闭/处置结果集/语句/连接对象,因此您需要返回Product对象引用或List<T>而不是ResultSet

例如,

public class Product
{
   private int id;
   private String name;
   .....
}

............

public List<Product> selectProductById (String pid) {

 ...
 List<Product> list=new ArrayList<Product>();

 try {
   String query = "select * from product where pid = ?";
   .....
   while(rs.next())
   {
      Product item=new Product();
      item.setId(rs.getInt(1));
      item.setName(rs.getString(2));
      list.add(item);
    } 
  ....
  return list;
}

答案 1 :(得分:0)

在finally块中,您将关闭结果集和连接对象,然后返回结果集obj。尝试在try块中返回结果集对象。

相关问题