2012-02-20 77 views
0

她是我的测试JSP代码和JavaBean DB函数代码:如何在jsp中打印来自javabean的结果集数据?

的jsp:

<% 

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

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

} 

%> 

的JavaBean:

公众的ResultSet selectProductById(字符串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的方法获取结果集,但出现错误。如何解决它?

感谢

回答

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; 
} 
+0

如果javaBean是应用程序范围,如果包含结果集的对象会消耗太多资源吗? – hkguile 2012-02-20 03:02:32

0

在finally块,你关闭结果集和连接对象,后来返回结果集obj。尝试返回try块中的resultset对象。

+1

这个问题已经有一个可接受的答案,解决相同的潜在问题 – 2012-10-03 13:42:54