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

时间:2014-02-27 17:40:41

标签: java sqlite select null

我无法让我的前端返回一个JOptionPane,如果用户查询我的SQLite数据库中不存在的ID并且显示该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");
           }

1 个答案:

答案 0 :(得分:0)

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

你的程序逻辑应该是这样的:

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