How to access a variable in mysql database from another class?

I am trying to access a variable from one class in another.

In my example below, I have 2 files, one called login.java and usermainpage.java.
I want to access a variable called sessionId that is in login.java from usermainpage class file.

I tried several methods but it is not working at all, in login class file, I declared sessionId as a public string and in the file I define it as equals to a data that I retrieved from my database. (If you see the code I am doing a database connection also).
I thought by returning sessionId at the end of the function I can now access this variable from all other java files but no, in my usermainpage.java file, I tried printing out sessionId and it displays nothing. Let me know of a solution, thank you.

// login.java file
public class login extends javax.swing.JFrame {
    public String sessionId;
    Connection con;
    PreparedStatement pst;
    ResultSet rs;

    private String LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            String query = "SELECT * FROM `accounts` WHERE username=? and password=?";
            con = DriverManager.getConnection("jdbc:mysql://localhost/restock", "root", "password");
            pst = con.prepareStatement(query);
            pst.setString(1, txtUsername.getText());
            pst.setString(2, txtPassword.getText());
            rs = pst.executeQuery();
            if(rs.next()){
                String userType = rs.getString("usertype");
                sessionId = rs.getString("id");
                System.out.print("##########" + sessionId + "##########"); //this prints out the id I want
                if(userType.equals("Admin")){
                    JOptionPane.showMessageDialog(this, "Login is successful as admin");
                    mainpage admin = new mainpage();
                    admin.setVisible(true);
                    dispose();
                } else{
                    JOptionPane.showMessageDialog(this, "Login is successful as user");
                    usermainpage user = new usermainpage();
                    user.setVisible(true);
                    dispose();
                }
            }
            else{
                JOptionPane.showMessageDialog(this, "Incorrect username or password");
                txtUsername.setText("");
                txtPassword.setText("");
            }
            
        } catch(HeadlessException | SQLException ex){
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
        
        return sessionId;
        
    }

}

//usermainpage.java file
public class usermainpage extends javax.swing.JFrame {

    private void RequestButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
          String type = txttype.getSelectedItem().toString();
          String name = txtname.getText();
          String quantity = txtquantity.getText();
          String status = "Pending";
          String userId;
        
          //Create new class object from login.java
          login testing = new login();
          userId = testing.sessionId;
          System.out.print("########## " + userId + "########## "); //this prints out null value
     }
}

EDIT: These are some of the problems I encountered based on the suggestions.

enter image description here

enter image description here

enter image description here

enter image description here

Upvotes: 0

Views: 480

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79435

There are so many problems with your code:

  1. You should always follow Java naming conventions e.g. you should name your class as Login instead of login. Similarly, the name of your method should be loginButtonActionPerformed instead of LoginButtonActionPerformed.

  2. I do not see any use of the parameter, java.awt.event.ActionEvent evt in your method, LoginButtonActionPerformed. I would remove it from its definition and the calls.

  3. You should avoid making variables public. You should keep sessionId as private or protected as per the requirement and create the public accessor and mutator for it as shown below:

    private String sessionId;
    
    public setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }
    
    public String getSessionId() {
        return sessionId;
    }
    
  4. You are returning the value of sessionId from the method, LoginButtonActionPerformed and therefore you need to call this method inside your method, RequestButtonActionPerformed as follows:

    login testing = new login();
    userId = testing.LoginButtonActionPerformed(evt);
    

    However, for this, you need to declare your method, LoginButtonActionPerformed as public.

  5. A better approach would be to declare LoginButtonActionPerformed as public void and then you can do:

    login testing = new login();
    testing.LoginButtonActionPerformed(evt);
    userId = testing.getSessionId();
    

Upvotes: 2

Related Questions