Mysql-java不能使用来自另一个类的连接方法



我目前是软件工程专业的一年级学生,在为大学开发项目时遇到了一些问题。我目前正在做一个netbeans项目,该项目允许用户登录并从mysql数据库中检索信息。我目前有一个单独的数据处理类,我已经在其中编写了连接方法,如下所示。然而,当我在Jframe类中创建数据处理程序的新对象并尝试调用连接方法时,它不允许我使用插入语句(见下文(,我在按钮后面编程了这些语句(以便从txtfields中检索信息(。然而,当我将连接方法移动到Jframe类时,它的工作非常好。我想知道我是不是遗漏了一些明显的东西,或者这只是一个糟糕的设计。

感谢您的支持!

private void connection(){
//from data handler class
try{
String mysqlUrl = "jdbc:mysql://localhost/test";
String username = "root";
String password = "";
con = DriverManager.getConnection(mysqlUrl, username, password);
}
catch(Exception e){
System.err.println("Got an exception");
System.err.println(e.getMessage());
}
}
}
private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {                                            
try{
Datahandler test = new Datahandler();
test.connection();
//create my mysql database connection

String query = "INSERT INTO User(customerStatus ,title, firstname, lastname, contactNo, email, username, password)" 
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
pst = con.prepareStatement(query);
pst.setString(1,"Beginner");
pst.setString(2,cmdGender.getSelectedItem().toString());
pst.setString(3,txtFirstname.getText());
pst.setString(4,txtLastname.getText());
pst.setString(5,txtPhone.getText());
pst.setString(6,txtEmail.getText());
pst.setString(7,txtUsername.getText());
pst.setString(8,txtPassword.getText());
pst.execute();
/* inserts the values username and password into a separate table in the database and
makes use of the to ensure that the login is sercure(I will possibly make a change to
how the structure of the databases work since there is an security issue here
*/
String query2 = "INSERT INTO Login(username, password)" 
+ "VALUES (?, ?)";
pst = con.prepareStatement(query2);
pst.setString(1,txtUsername.getText());
pst.setString(2,txtPassword.getText());
pst.execute();

JOptionPane.showMessageDialog(null, "Registration completed!");
//reset registration boxes into empty text
txtFirstname.setText("");
txtLastname.setText("");
txtPhone.setText("");
txtEmail.setText("");
txtUsername.setText("");
txtPassword.setText("");
}
catch (Exception e){
System.err.println("Got an exception");
System.err.println(e.getMessage());
JOptionPane.showMessageDialog(null, "Something went wrong try to register again");
}
}                                           

您的getConnection()方法没有返回任何内容。相反,它将连接对象设置为该特定类中的obejct-con。

con = DriverManager.getConnection(mysqlUrl, username, password);

这就是为什么您可以在Jframe类中使用它,因为它包含在getConnection()方法中设置的con属性。但是在您的新类中,没有一个文件con具有正确的连接对象。

修改方法getConnection(),使其返回连接对象,并使用此方法返回的连接对象进行进一步处理。

最新更新