为什么 while(rs.next()) 只返回最后一行数据?

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

在我的代码中,while(rs.next()) 仅返回最后一行数据。我也尝试过使用 if(rs.next()) 但它只会给我第一行的数据。

请帮我解决这个问题。

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);

您每次迭代都会覆盖 jb 中的值。 RS 中的最后一个元素是写入 jb 的最后一个元素 - 当您使用 jb 时,只剩下最后一个元素。

我不确定您需要将结果用于什么目的,但您可以使用 Strings 的二维数组来存储所有值。大致如下:

根据评论更新,对问题有了新的理解

    ResultSet rs = stmt.executeQuery();

    // stores the results into a collection
    List<JRadioButton[]> radioButtonList = new ArrayList<>();
    List<JLabel> labelList = new ArrayList<>();

    // iterate thru result set        
    while(rs.next()){
        // prints to console
        System.out.println(rs.getInt(1) + " " + rs.getInt(8));

        // init label
        JLabel l = new JLabel();
        l.setBounds(30,40,450,20);

        // set text for label
        l.setText(rs.getInt(2) + " " + rs.getString(3));

        // at least one element, set to visible
        l.setVisible(true);

        // store values from rs into an array of radio buttons
        JRadioButton[] jb = new JRadioButton[5];
        jb[0].setText(rs.getString(4));
        jb[1].setText(rs.getString(5));
        jb[2].setText(rs.getString(6));
        jb[3].setText(rs.getString(7));

        // store object in list for future use
        radioButtonList.add( jb );

        //store label in list
        labelList.add(l);
    }


    // now loop thru the lists
    for(JRadioButton[] jbArray : radioButtonList){
        // your code here - update to suit your needs
        // jbArray[4].setBounds(50,80,200,20); // not sure what the values should be here
    }

    for(JLabel jLabel: labelList){
        // your code here - update to suit your needs
        // jLabel.setBounds(50,80,200,20); // not sure what the values should be here            
    }