简体   繁体   English

Java / MySQL中的if / else语句

[英]if/else statement in Java/MySQL

I am try to create a function where you enter a student_id saved in a MySQL database("student_id") and you will see the student name and what classes they are enrolled in. I am having trouble with the if/else statement, though. 我尝试创建一个函数,在其中输入保存在MySQL数据库中的student_id(“ student_id”),您会看到学生姓名及其注册的班级。不过,if / else语句给我带来了麻烦。 It works if the student_id entered is in the database, but if you enter an ID that isn't, it does not print out the error message I want; 如果输入的student_id在数据库中,则该方法有效,但如果输入的ID不是,则它不会打印出我想要的错误消息; it instead just goes back to the menu. 相反,它只是返回菜单。

System.out.println("\nStudent Enrollment\n");
      try {
          Scanner input = new Scanner(System.in);
          System.out.println("Enter Student ID to See What Classes they are enrolled in: ");
          String user_entered_student_id = input.nextLine();

          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ClassSelector?autoReconnect=true&useSSL=false", "", "");
          Statement myStmt = con.createStatement();

          ResultSet rs;
          rs = myStmt.executeQuery("SELECT student_id, student_name, class_id, classname  FROM ClassSelector.student_x_class WHERE student_id = " + user_entered_student_id);
          while(rs.next()){
              String studentInClass = (rs.getString("student_id") + "\t" + rs.getString("student_name") + "  " + rs.getString("class_id") + " " + rs.getString("classname"));
              if(!user_entered_student_id.equals("ClassSelector.students.student_id")){
                 System.out.println(studentInClass); 
              }
              else{
              System.out.println("This Student does not Exist!");
              }
          }   
      }

You have your logic in the while loop which will never be entered in no rows exist. while循环中有自己的逻辑,永远不会在没有行的情况下输入逻辑。

try 尝试

 boolean found = false;
 while(rs.next()){
              if(!user_entered_student_id.equals("ClassSelector.students.student_id")){
                 System.out.println(studentInClass); 
                 found = true;
                 break; // ??  Is this unique?
              }
  } 

  if (!found) {
      System.out.println("This Student does not Exist!");
      return false; // ???
  }
  return true; // ???

Of course if you are only look for one unique record then you can use if instead of while 当然,如果你只是寻找一个独特的记录,那么你可以使用if不是while

The main reason is because if your connection will return an empty result set then the loop while(rs.next()){ } will not get executed. 主要原因是因为如果您的连接将返回空结果集,则循环while(rs.next()){ }将不会执行。

rs.next returns false when there are no matching entries in the database. 如果数据库中没有匹配的条目,则rs.next返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM