Hoody
Hoody

Reputation: 3072

How to retrieve username and password in another class?

The following LOGINFORM class stores the correct username and password which were used to login to a GUI.

LOGIN CLASS....

public class LoginForm extends javax.swing.JFrame {

String username;
String password;

//rest of code here

how do i retrieve the Loginform username and password to be used in the prepared statement in another class in the line ("SELECT * FROM AcademicInfo where Email=? and Password=?"); replacing the ? , which would enable me to obtain a specific field in from sql database?

RETRIEVE CLASS....

public void retrieveAcademic() {

try {
pst = con.prepareStatement("SELECT * FROM AcademicInfo where Username=? and Password=?");
rs = pst.executeQuery();
while (rs.next()) {
          title = (rs.getString(2));
          forename = (rs.getString(3));
          surname = (rs.getString(4));
          role = (rs.getString(5));
          room = (rs.getString(6));
          page = (rs.getString(7));
          hours = (rs.getString(8));
          phone = (rs.getString(9));
          mobile = (rs.getString(10));
          email = (rs.getString(11));


         } //end while
  } 

Upvotes: 0

Views: 857

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272347

Loginform needs a reference to an instance of the class containing the retrieveAcademic() method. How you create/pass that reference depends enormously on the structure of your application (e.g. via dependency injection, a simple construction etc.).

Note that an alternative is for your db-related class to have a reference to LoginForm and call appropriate getters e.g. getPassword() and getUsername()

I suspect however that you want some sort of model object containing these credentials such that other components can access them as/when required. Your login form is transitory and you may have other means of logging in in the future(e.g. you may have a web service or similar). I realise this is perhaps thinking far ahead, but you get the idea.

The simplest way to then pass the username/password is to pass them as 2 arguments e.g.

db.retrieveAcademic(username, password);

and in the method call PreparedStatement.setString() for the appropriate fields.

(you may want to wrap the username and password fields into a separate object Credentials or similar, but that's for later)

Upvotes: 2

Related Questions