如果数据库中不存在 ID,则返回消息对话框



如果用户查询我的SQLite数据库中不存在的ID,则无法让我的前端返回一个JOptionPane,说ID不存在,并显示ID的记录(如果存在)。我尝试了isEmpty(),这显然是不正确的。

我的代码:

        String SelectRecords = "SELECT * FROM Student WHERE ID_Num = ?";
        String ID_Number = id_input.getText();
        PreparedStatement ps = c.prepareStatement(SelectRecords);
        ps.setString(1, ID_Number);
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
           String IDNum = rs.getString("ID_Num");
           String LastName = rs.getString("Stud_Name_Last");
           String FirstName = rs.getString("Stud_Name_First");
           String DaysPresent = rs.getString("days_present");
           String DaysAbsent = rs.getString("days_absent");
           String DropStatus = rs.getString("drop_status");
           String Course = rs.getString("course");
           String LastAttended = rs.getString("last_attended_class");

           String StudentRecords = "ID Number: "+IDNum+"n"+"Last Name"+LastName+"n"+"First Name: "+FirstName+"n"+"Days Present: "+DaysPresent+"n"+"Days Absent: "+DaysAbsent+"n"+"Drop Status: "+DropStatus+"n"+"Course: "+Course+"n"+"Last Attended On: "+LastAttended;
           Output_Label.setText(LastName+", "+FirstName+"(Retrieving...)");

           if(rs.next() == true){
               JOptionPane.showMessageDialog(null, StudentRecords, LastName+", "+FirstName, JOptionPane.INFORMATION_MESSAGE);

           }
           else{
               JOptionPane.showMessageDialog(null, "Does not exist");
           }

您调用rs.next()两次,这仅在至少有两个记录时才有意义。假设只能有一个具有特定 ID 的学生,则while循环也没有意义。

程序的逻辑可能如下所示:

ResultSet rs = ps.executeQuery();
if (rs.next()) {
    // found
} else {
    // not found
}

相关内容

  • 没有找到相关文章

最新更新