有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何从同一列java和sql中获取信息

因此,我试图创建一个应用程序,我的登录用户只需输入一个pin。我想根据他们的职位,打开一个新的JFrame。在我的数据库中,我在users表中创建了一个名为“occupation”的列。如何获取该列中的信息,以便根据其职务创建不同的IF语句


     try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurantdb", "root","");
            String sql = "Select * from users where pin=?";
            PreparedStatement pst = con.prepareStatement(sql);
            pst.setString(1, PinField.getText());
            ResultSet rs = pst.executeQuery();
            if (rs.next()){
                JOptionPane.showMessageDialog(null, "Login Succesful");
                /*if (occupation = "Server") {

                New ServerWindow
                }
                */
            }
            else{
                JOptionPane.showMessageDialog(null, "Login Failed");
                PinField.setText("");

            }
            con.close();

        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }
    }    

共 (1) 个答案

  1. # 1 楼答案

    Preparedstatement job=con.prepareStatement("SELECT 
    Occupation FROM USERS WHERE PIN=?"); 
    job.setString(1,PinField.getText());
    
    try(ResultSet myJob=job.executeQuery())
    {
     if(myJob.next())
     {
      String theJob=myJob.getString("Occupation");
    
      if(theJob.equals("Whatever u want");{/*open frame 1*/}
      if(theJob.equals("Whatever u want 2");{/*open frame 2*/}
     }
    }
    

    或者

    因为你在结果集中已经有了完整的数据,所以你可以这样做

      String theJob=rs.getString("Occupation");
    
      if(theJob.equals("Whatever u want");{/*open frame 1*/}
      if(theJob.equals("Whatever u want 2");{/*open frame 2*/}