簡體   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