gpt4 book ai didi

Java IF ELSE 语句

转载 作者:行者123 更新时间:2023-12-01 15:30:23 25 4
gpt4 key购买 nike

快速提问。我得到了下面的代码,它检查数据库中给定的 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");
}

关于Java IF ELSE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9589697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com