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

时间:2016-10-12 04:06:46

标签: java jdbc resultset

在我的代码中,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);

1 个答案:

答案 0 :(得分:0)

每次迭代都会覆盖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            
    }