[英]Java IF ELSE statements
快速提問。 我在下面獲得了一個代碼,該代碼與數據庫一起檢查數據庫中是否有給定的ID,如果有,它將檢索該ID的所有出勤歷史記錄,否則,如果該ID在數據庫中不存在,則應顯示一條錯誤消息。 。 但是,我得到的代碼總是說記錄已附加,然后無論ID是否存在也都會顯示錯誤消息。 我想我可能必須更改代碼等的順序? 您能否提一些建議?
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();
}
}
});
您將反復調用rs.next()
直到它返回false(否則您將永遠不會退出while循環)-然后,您將再次調用rs.next()
。 那么,您為什么期望它返回true?
我懷疑您想要類似的東西:
if (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);
} else {
JOptionPane.showMessageDialog(frmAttendanceHistory,
"A record for the given Student ID doesn't exist");
}
您正在執行第二個rs.next,如果存在,它將轉到第二個記錄。 如果只有一個(已經在您的應用程序中進一步消耗了),那么它將失敗並給您帶來成功,然后是失敗。
while ( rs.next() ) {
其次是
if (!rs.next()) {
沒有任何意義,因為if
會一直執行。 您的循環將繼續進行,直到rs.next()
返回false。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.