如何从另一个类访问MySQL数据库中的变量?

huangapple go评论69阅读模式
英文:

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 the login class file, I declared sessionId as a public String, and in the file, I define it as equals to 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 a new class object from login.java
        login testing = new login();
        userId = testing.sessionId;
        System.out.print("########## " + userId + "##########"); // this prints out a null value
    }
}

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

如何从另一个类访问MySQL数据库中的变量?

如何从另一个类访问MySQL数据库中的变量?

如何从另一个类访问MySQL数据库中的变量?

如何从另一个类访问MySQL数据库中的变量?

英文:

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.
<br>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).
<br>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 = &quot;SELECT * FROM `accounts` WHERE username=? and password=?&quot;;
con = DriverManager.getConnection(&quot;jdbc:mysql://localhost/restock&quot;, &quot;root&quot;, &quot;password&quot;);
pst = con.prepareStatement(query);
pst.setString(1, txtUsername.getText());
pst.setString(2, txtPassword.getText());
rs = pst.executeQuery();
if(rs.next()){
String userType = rs.getString(&quot;usertype&quot;);
sessionId = rs.getString(&quot;id&quot;);
System.out.print(&quot;##########&quot; + sessionId + &quot;##########&quot;); //this prints out the id I want
if(userType.equals(&quot;Admin&quot;)){
JOptionPane.showMessageDialog(this, &quot;Login is successful as admin&quot;);
mainpage admin = new mainpage();
admin.setVisible(true);
dispose();
} else{
JOptionPane.showMessageDialog(this, &quot;Login is successful as user&quot;);
usermainpage user = new usermainpage();
user.setVisible(true);
dispose();
}
}
else{
JOptionPane.showMessageDialog(this, &quot;Incorrect username or password&quot;);
txtUsername.setText(&quot;&quot;);
txtPassword.setText(&quot;&quot;);
}
} 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 = &quot;Pending&quot;;
String userId;
//Create new class object from login.java
login testing = new login();
userId = testing.sessionId;
System.out.print(&quot;########## &quot; + userId + &quot;########## &quot;); //this prints out null value
}
}

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

如何从另一个类访问MySQL数据库中的变量?

如何从另一个类访问MySQL数据库中的变量?

如何从另一个类访问MySQL数据库中的变量?

如何从另一个类访问MySQL数据库中的变量?

答案1

得分: 2

有很多问题存在于你的代码中:

  1. 你应该始终遵循Java命名约定,例如,你应该将类命名为Login而不是login。同样,你的方法名称应该是loginButtonActionPerformed而不是LoginButtonActionPerformed

  2. 我在你的方法LoginButtonActionPerformed中看不到参数java.awt.event.ActionEvent evt的任何用途。我建议从方法定义和调用中将其删除。

  3. 你应该避免将变量设置为public。你应该将sessionId保持为privateprotected,并按照下面的方式创建public访问器和修改器:

    private String sessionId;
    
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }
    
    public String getSessionId() {
        return sessionId;
    }
    
  4. 你从方法LoginButtonActionPerformed中返回了sessionId的值,因此你需要在你的方法RequestButtonActionPerformed中调用此方法,如下所示:

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

    然而,为此,你需要将你的方法LoginButtonActionPerformed声明为public

  5. 更好的方法是将LoginButtonActionPerformed声明为public void,然后你可以这样做:

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

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();
    

huangapple
  • 本文由 发表于 2020年8月10日 01:45:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63329508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定