Search code examples
javasqldatabaseswitch-statementresultset

Java only displaying one SQL result using switch


Hi I'm trying to get the results from a database to be set in different text fields based on the time. E.g. this is an appointment viewer that I have retrieved the data for a certain date but it is only putting the first result in the text box.

    private void appointmentsView(){

    String sqldate  = ((JTextField)appointmentDate.getDateEditor().getUiComponent()).getText();

    try{

    String sql="SELECT appointment_tbl.app_date, appointment_tbl.app_time, patient.Title, patient.first_name, patient.surname, patient.dob FROM appointment_tbl INNER JOIN patient ON appointment_tbl.Customer_ID = patient.Customer_ID where app_date LIKE ('%' || ? || '%') ";
    pst=conn.prepareStatement(sql);
    pst.setString(1,sqldate);
    rs=pst.executeQuery();

    if(rs.next()){
        String appTime=rs.getString("app_time");
        String title=rs.getString("Title");
        String fName=rs.getString("first_name");
        String sName=rs.getString("surname");
        String dob=rs.getString("dob");

        switch (appTime) {
            case "09:00":
                time0900.setText(title+" "+fName+" "+sName+" "+dob);
                break;
            case "09:30":
                time0930.setText(title+" "+fName+" "+sName+" "+dob);
                break;
            case "10:00":
                time1000.setText(title+" "+fName+" "+sName+" "+dob);
                break;
            case "10:30":
                time1030.setText(title+" "+fName+" "+sName+" "+dob);
                break;
            case "11:00":
                time1100.setText(title+" "+fName+" "+sName+" "+dob);
                break;

        }



    }
    }catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
    }

}


Solution

  • Your code if(rs.next()) only returns the first result row. You should replace it with while(rs.next()) to create a loop that iterates over all results.