Home > Software design >  Transfer ResultSet from class A to class B in Java
Transfer ResultSet from class A to class B in Java

Time:02-23

I am programming on a LoginForm with a MySQL database in Java. It all works well and now I wanted to add permissions. If someone logs in, the data from a specific user will be inserted in a Resultset. The problem is that I need to give the Resultset to the next class that I have the permissions in the other class and can say what the user is allowed to see. And the only clue I have is that if I call up the other class that I send it within it.

The Resultset

// That Code part is from Class A (In the Project LoginPage.java)
public void loginfunc() throws Exception {

    String userID = userIDField.getText();
    String password = String.valueOf((userPasswordField.getPassword()));
    Connection con = getConnection();
    try {
        PreparedStatement statementuser = con.prepareStatement("SELECT * FROM uprtable WHERE username = '" userID "'");
        //TODO transfer Resultset "result" to Class "WelcomePage"
        ResultSet result = statementuser.executeQuery();

How I call up the other class

if (result.getString("username").equals(userID));

if (result.getString("password").equals(password)) {
    frame.dispose();
    String userresult = result.getString("username");
    int rankresult = result.getInt("rank");
    WelcomePage welcomePage = new WelcomePage(result);
}

The error I get is

'WelcomePage()' in 'com.company.WelcomePage' cannot be applied to '(java.sql.ResultSet)'

CodePudding user response:

From the error message it seems that WelcomePage class does not have a constructor that can accept a ResultSet. You need to write a constructor in WelcomePage that can accept the ResultSet, the default constructor accepts no arguments.

For instance:

public class WelcomePage{
    private ResultSet resultSet;
   
    WelcomePage(ResultSet resultSet){
        this.resultSet=resultSet;
    }


}

PS: Τhis approach will work, but it would be better to parse the ResultSetinside the class that it was first referenced (Class A in this case), get all the required information release the database resources and then pass the needed data to the other class (Class B) in another way e.g. in a dedicated Java Bean.

  • Related