p_S p_S - 1 month ago 10
Java Question

Why while(rs.next()) returning only last row data?

In my code, while(rs.next()) is returning only the last row data. I have also tried using if(rs.next()) but it will give me only the data of the first row.

Please help me resolve this.

ResultSet rs=stmt.executeQuery();
{ while(rs.next())
{ System.out.println(rs.getInt(1)+" "+rs.getInt(8));

l.setText(rs.getInt(2)+" "+rs.getString(3));
jb[0].setText(rs.getString(4));
jb[1].setText(rs.getString(5));
jb[2].setText(rs.getString(6));
jb[3].setText(rs.getString(7));
l.setVisible(true);
}
}

l.setBounds(30,40,450,20);
for(int i=0,j=0;i<=90;i+=30,j++)
jb[j].setBounds(50,80+i,200,20);

Answer

You keep overwriting the values in jb with each iteration. The last element in the RS is the last one written to jb - by the time you are using jb only the last element is left in it.

I am not sure what you need to use the results for but you can use a 2D array of Strings to store all the values. Something along the lines of:

ResultSet rs=stmt.executeQuery();
String[][] jbs = new String[90][30];  // assuming sizes based on for loop below
// keeps track of the rows 
int rowNum = 0;

while(rs.next()){
     System.out.println(rs.getInt(1)+" "+rs.getInt(8));

        l.setText(rs.getInt(2)+" "+rs.getString(3));
        jb[rowNum][0].setText(rs.getString(4));
        jb[rowNum][1].setText(rs.getString(5));
        jb[rowNum][2].setText(rs.getString(6));
        jb[rowNum][3].setText(rs.getString(7));
        l.setVisible(true);
      rowNum++;
}   

l.setBounds(30,40,450,20);
// reset rowNum
rowNum = 0;

// now use the values in the 2d array to set the bounds 
// of whatever you need to use the values for
for(int i=0,j=0;i<=90;i+=30,j++){
    jb[j][0].setBounds(50,80+i,200,20);
    jb[j][1].setBounds(50,80+i,200,20);
    jb[j][2].setBounds(50,80+i,200,20);
    jb[j][3].setBounds(50,80+i,200,20);
    jb[j][4].setBounds(50,80+i,200,20);
}