Discussions

Web tier: servlets, JSP, Web frameworks: Problem with ResultSets and while loops

  1. Problem with ResultSets and while loops (4 messages)

    I have the following code:
    <%
    cpartner.connect();
    ResultSet rsPartner = cpartner.getPartner();
    ResultSet rsPartnerCategories = cpartner.getPartnerCategories();
    while (rsPartnerCategories.next())
    {
    %>

    <TR><TD colspan="2"><%= rsPartnerCategories.getString("PartnerCategoryName") %></TD></TR>

    <%
    while (rsPartner.next())
    {
    %>

    <TR><TD valign="top"><img src="images/arrow.gif" width="10" height="10" alt=""></TD>
    <TD><%= rsPartnerCategories.getString("PartnerCategoryName") %>|<%= rsPartner.getString("PartnerCategoryName") %>|<%= rsPartner.getString("PartnerName") %></A><BR><BR><P></TD></TR>

    <%
    }
    }
    %>

    I was expecting to have the outer while spit out the results (of which there are three) and within each of those results have the inner while spit out six results.

    Instead I get:
    OuterLoopItem1
    - InnerLoopItem1
    - InnerLoopItem2
    - InnerLoopItem..
    - InnerLoopItem6
    OuterLoopItem2
    OuterLoopItem3

    Can anyone help please?
  2. Of course it doesn't work as you expected because rsPartner output the 6 inner loop items, it moves to the end of the ResultSet. So it doesn't output anything in the next iteration.

    In order to do what you're expecting, iterates thru rsPartner first and store them in a Collection, then use this Collection to populate the inner loop.
  3. Thank you.

    I was wondering if that was the case, in that it reached the end of the resultset, is there any way to get it to go back to the beginning instead of putting it in a collection?

    Just so I know?

    Thanks,
    CC
  4. Hello,

    Thanks for your comment on the Collection. If I need to store multiple columns, then does that mean I should create a two dimensional array?

    Thanks,
    CC
  5. 2-dimensional array is one way to do it, you can also use Collection of Collection if you like (e.g. HashMap of ArrayList, then you can store the column name as the key).