英文:
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.
英文:
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 = "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.
答案1
得分: 2
有很多问题存在于你的代码中:
-
你应该始终遵循Java命名约定,例如,你应该将类命名为
Login
而不是login
。同样,你的方法名称应该是loginButtonActionPerformed
而不是LoginButtonActionPerformed
。 -
我在你的方法
LoginButtonActionPerformed
中看不到参数java.awt.event.ActionEvent evt
的任何用途。我建议从方法定义和调用中将其删除。 -
你应该避免将变量设置为
public
。你应该将sessionId
保持为private
或protected
,并按照下面的方式创建public
访问器和修改器:private String sessionId; public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getSessionId() { return sessionId; }
-
你从方法
LoginButtonActionPerformed
中返回了sessionId
的值,因此你需要在你的方法RequestButtonActionPerformed
中调用此方法,如下所示:login testing = new login(); userId = testing.LoginButtonActionPerformed(evt);
然而,为此,你需要将你的方法
LoginButtonActionPerformed
声明为public
。 -
更好的方法是将
LoginButtonActionPerformed
声明为public void
,然后你可以这样做:login testing = new login(); testing.LoginButtonActionPerformed(evt); userId = testing.getSessionId();
英文:
There are so many problems with your code:
-
You should always follow Java naming conventions e.g. you should name your class as
Login
instead oflogin
. Similarly, the name of your method should beloginButtonActionPerformed
instead ofLoginButtonActionPerformed
. -
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. -
You should avoid making variables
public
. You should keepsessionId
asprivate
orprotected
as per the requirement and create thepublic
accessor and mutator for it as shown below:private String sessionId; public setSessionId(String sessionId) { this.sessionId = sessionId; } public String getSessionId() { return sessionId; }
-
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
aspublic
. -
A better approach would be to declare
LoginButtonActionPerformed
aspublic void
and then you can do:login testing = new login(); testing.LoginButtonActionPerformed(evt); userId = testing.getSessionId();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论