while loop in a while loop

S

Steven

Hi All,

I have the following situation:


while(rs.next()) { //loop1

while(rs2.next()) {
//loop 2
}

}



It seems like loop 2 is only beeing used once. Should I after loop2 put the
cursor back to the beginning? if so, how do I do that?

Thanks!
 
B

bugbear

Steven said:
Hi All,

I have the following situation:


while(rs.next()) { //loop1

while(rs2.next()) {
//loop 2
}

}

The architypal loop (for a List eg ArrayList of Blah objects) is:

for(Iterator bi = list.iterator(); bi.hasNext(); ) {
Blah myBlah = (Blah)bi.next();
 
H

Hikikomori

Depending on your database vendor and JDBC driver version, you might or
might not be able to reset the ResultSet cursor. If the the drivers
allow, you can create a ResultSet with a flexible cursor by calling:

Statement stmt = con.createStatement(

ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
// rs will be scrollable, will not show changes made by others,
// and will be updatable

The method ResultSet.first() moves the cursor to the first row in the
ResultSet object. However, ResultSets are created with cursors placed
before the first record, so you will probably get inaccurate results.

For more information please refer to the Javadoc for ResultSet and
Connection.
 
R

Ryan Stewart

Steven said:
Hi All,

I have the following situation:


while(rs.next()) { //loop1

while(rs2.next()) {
//loop 2
}

}



It seems like loop 2 is only beeing used once. Should I after loop2 put the
cursor back to the beginning? if so, how do I do that?
Are you getting both ResultSets from the same Statement?
 
K

Kevin McMurtrie

Hi All,

I have the following situation:


while(rs.next()) { //loop1

while(rs2.next()) {
//loop 2
}

}



It seems like loop 2 is only beeing used once. Should I after loop2 put the
cursor back to the beginning? if so, how do I do that?

Thanks!

Well, yeah. You depleted rs2 all at once. It won't loop again until
it's populated with more values.

Moving the cursor is often database-specific. You'll need to read the
JDBC and database documentation. You could also save the results into a
List so it can be read multiple times.
 
T

Tim Slattery

Steven said:
Hi All,

I have the following situation:


while(rs.next()) { //loop1

while(rs2.next()) {
//loop 2
}

}



It seems like loop 2 is only beeing used once. Should I after loop2 put the
cursor back to the beginning? if so, how do I do that?

Add:

rs2.beforeFirst();

after the end of the interior loop
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top