2012-02-20 75 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