2012-05-16 74 views
0
Comment comment; 
    ArrayList<Comment> commentList = null; 

    try{ 
     ConnectionFactory myFactory = ConnectionFactory.getFactory(); 
     Connection conn = myFactory.getConnection(); 
     int i = 1; int j = 1; int k = 1; 

     PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM COMMENT WHERE deletestatus = 0 and workid = ?"); 

     PreparedStatement pstmtLName = conn.prepareStatement("SELECT * FROM LEADER WHERE leaderid = ?"); 

     PreparedStatement pstmtMName = conn.prepareStatement("SELECT * FROM MEMBER WHERE memberid = ?"); 

     pstmt.setInt(i++, Integer.parseInt(projid)); 

     ResultSet rs = pstmt.executeQuery(); 
     System.out.print(rs); 
     commentList = new ArrayList<Comment>(); 
     while(rs.next()) 
      { 
       comment = new Comment(); 
       comment.setDetails(rs.getString("details")); 
       comment.setDateadded(rs.getTimestamp("dateadded")); 
       comment.setUrgency(rs.getInt("urgency")); 



       if(rs.getInt("leaderid") != 0){ 
        comment.setLeaderid(rs.getInt("leaderid")); 

        pstmtLName.setInt(j++, rs.getInt("leaderid")); 

        ResultSet rs2 = pstmtLName.executeQuery(); 


        if(rs2.next()){ 
        comment.setFullname(rs2.getString("firstname") +" " + rs2.getString("lastname")); 
        } 
       } 
       if(rs.getInt("memberid") != 0) { 
        comment.setMemberid(rs.getInt("memberid")); 

        System.out.print("in the loop"); 

        pstmtMName.setInt(j++, rs.getInt("memberid")); 
        ResultSet rs3 = pstmtMName.executeQuery(); 

        if(rs2.next()){ 
        comment.setFullname(rs3.getString("firstname") +" " + rs3.getString("lastname")); 
        } 

       } 

       comment.setProjid(Integer.parseInt(projid)); 
       commentList.add(comment); 
      } 



     return commentList; 
    } 

上面的代碼的問題是,它只返回結果集的第一個結果。不完整的ResultSet數據

當我刪除WHILE(RS.NEXT)子句中的IF子句時,它返回了所有需要的結果,但返回了不完整的信息,因爲我還需要if語句中的查詢。

請你幫助,如果你們知道確切的問題,並告訴我,如果你們需要更多的信息。謝謝!

回答

2

這裏,這個問題似乎在

pstmtLName.setInt(j++, rs.getInt("leaderid")); 
pstmtMName.setInt(j++, rs.getInt("memberid")); 

j的值將爲每個真實的情況,直到循環迭代增加。 因此,它會增加您準備好的陳述的parameterIndex

應該

pstmtLName.setInt(1, rs.getInt("leaderid")); 
pstmtMName.setInt(1, rs.getInt("memberid")); 
+0

聲明是在這種背景下錯了地方。這個解決方案完美運作感謝那! :) – gwafito

+0

你WEL-來 –

2

您已經定義int k但沒有使用它。我假設你想用它來設置memberid參數。
變化

pstmtMName.setInt(j++, rs.getInt("memberid")); 

pstmtMName.setInt(k++, rs.getInt("memberid")); 

,它應該是工作。

而且我不知道爲什麼你使用i++j++k++當在查詢可見的只有一個參數標記?設置語句帕拉姆值。你應該直接使用pstObject.setInt(1, ...。否則,如果rs獲取比創紀錄的地方leaderid != 0memberid != 0,它們將導致對標記索引的增量多,說pstObject.setInt(2, ...,這是在您的查詢的情況下無效的參數,並拋出和SQLException

由於您在while循環中反覆使用相同的pstObject,我想建議使用pstObject.clearParameters()來清除當前參數值。雖然這是可選的,但在某些情況下,立即釋放當前參數值使用的資源非常有用。

+0

道歉的錯誤聲明。我真的不需要那裏的k。我希望代碼只能用於其中一個IF子句,但是,如果數據庫中發生任何異常情況,我不會將其作爲其他值,否則錯誤標記將會減少。 雖然感謝pstObject的建議!將會把它放在那裏!謝謝! – gwafito