-1

I have a database with users and each has a role. U for user and A for admin. I have a method in on class called getRole() which gets the role of a user ad returns it as String. In an other class I call this method, save its result to a String and then test that String. If it is A (admin) then proceed. The problem is that the String returns A, but the programm doesn't continue. What is wrong here?

getRole() Method:

public String getRole() throws SQLException {

    userid = "c##lambros";
    password = "16111111";
    jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    conn = DriverManager.getConnection(jdbcUrl, userid, password);
    checkRole = "SELECT role FROM users where username = '" + usernameF.getText() + "' AND password = '" + passwordF.getText() + "' ";
    System.out.println(checkRole);
    stmt = conn.createStatement();
    rset = stmt.executeQuery(checkRole);
    while (rset.next()){
    role = rset.getString(1);
    System.out.println("The User's Role is " + role);
    }
     return role;
    }

IF Statement:

    Login login = new Login();
    TermResultsFromDB terms = new TermResultsFromDB();
    String role;
    try {

        role = login.getRole();
        System.out.println(role);

        if(role=="A"){
        terms.getTerms(query);
        terms.setVisible(true);
        terms.setLocation(z, y);
        terms.pack();
        }

        else if (role!="A")
            System.out.println("Sorry! Not sufficient Privileges!");

    } catch (SQLException f) {
    }
Lambros
  • 151
  • 2
  • 14

3 Answers3

2

== operator compares references, so that

role == "A"

will always return false, as role is a different object than "A". Instead, use equals to compare your Strings.-

if("A".equals(role)) {

...

else if (!"A".equals(role)) {

More about comparing strings here.

ssantos
  • 16,001
  • 7
  • 50
  • 70
0

I think may be its because of case sensitive.

so you can use

if(role.equalsIgnoreCase("A"))
{
 //
}
else if(role.equalsIgnoreCase("A"))
{
 //
}
Jojo John
  • 410
  • 1
  • 5
  • 14
0

first check String A in role variable is in upper case ? if not then use this

if(role.toUpperCase().equals("A")) {
// statement
} else {
// statement
}
Mohsin AR
  • 2,998
  • 2
  • 24
  • 36