Quick question. I got a code below, which checks with a database whether a given ID is available in the database, if so, it retrieves all attendance histories for the ID, otherwise if the ID didn’t exist in the database it should display an error message. The code I got however, always says that the record has been attached, and then displays the error message as well regardless whether the ID exists or not. I think I probably have to change the order of the code or such? Could you please advise?
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
@SuppressWarnings("unused")
public void actionPerformed(ActionEvent arg0) {
String studentID = textField.getText();
try {
Statement st = con.con.createStatement();
ResultSet rs = st.executeQuery("SELECT StudentID, date FROM attendance WHERE StudentID ="+textField.getText());
while ( rs.next() ) {
String student = rs.getString("StudentID");
String date = rs.getString("date");
System.out.println(student+"");
System.out.println(date);
}
JOptionPane.showMessageDialog(frmAttendanceHistory, "Attendance has been registered.");
frmAttendanceHistory.setVisible(false);
if (!rs.next()) {
JOptionPane.showMessageDialog(frmAttendanceHistory, "A record for the given Student ID doesn't exist");
}
}
catch (SQLException e) {
JOptionPane.showMessageDialog(frmAttendanceHistory, "Attendance couldn't be registered. Please try again!");
e.printStackTrace();
}
}
});
You’re repeatedly calling
rs.next()until it returns false (as otherwise you’ll never get out of the while loop) – then you’re callingrs.next()again. Why would you expect it to return true then?I suspect you want something like: