繁体   English   中英

Java / MySQL中的if / else语句

[英]if/else statement in Java/MySQL

我尝试创建一个函数,在其中输入保存在MySQL数据库中的student_id(“ student_id”),您会看到学生姓名及其注册的班级。不过,if / else语句给我带来了麻烦。 如果输入的student_id在数据库中,则该方法有效,但如果输入的ID不是,则它不会打印出我想要的错误消息; 相反,它只是返回菜单。

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!");
              }
          }   
      }

while循环中有自己的逻辑,永远不会在没有行的情况下输入逻辑。

尝试

 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; // ???

当然,如果你只是寻找一个独特的记录,那么你可以使用if不是while

主要原因是因为如果您的连接将返回空结果集,则循环while(rs.next()){ }将不会执行。

如果数据库中没有匹配的条目,则rs.next返回false。

暂无
暂无

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

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