2012-02-20 15 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のメソッドから結果セットを取得しようとしていますが、エラーがあります。どのようにそれを修正するには?あなたの代わりにResultSetProductオブジェクト参照またはList<T>を返す必要があるので、あなたが/結果セット/声明を配置/接続オブジェクトをクローズしている

おかげ

答えて

1

。 finallyブロックで

例えば

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

0

、あなたは結果セットと接続オブジェクトを閉じて、後で戻ってきています結果セットobj。 tryブロック内のresultsetオブジェクトを返すようにしてください。

+1

この質問には、同じ可能性のある修正に対応する受け入れられた回答が既にあります –

関連する問題