0

Im trying to make a conditional statement in my java GUI program. I was already able to make connection with my database db2 and also able to execute query to obtain a result set.

The problem is that when i use a table data to compare with a string in a conditional statement (if), It always returns false and goes to else clause even though the data from the resultset is identical to the string im comparing it to.

I have written the code below.

String query3 ="select * from module where uname='ADMIN' and modulename='SETADMIN'";
                PreparedStatement pst2 = conn.prepareStatement(query3);
                ResultSet rs2=pst2.executeQuery();
                rs2.next();
                if (rs2.getString(1)=="ADMIN"){
                    JOptionPane.showMessageDialog(null, "if statement working");
                }
                else{
                    JOptionPane.showMessageDialog(null, "if statement not working");
                }

the resultset that will be obtained by the query would look like this

**UNAME   MODULENAME    CANADD   CANEDIT   CANDELETE**
  ADMIN     SETADMIN       T        T           T

everything else in the program seems fine except for the if clause always returning false and going straight to else clause

Any help would be much appreciated :)

SoulRider
  • 145
  • 2
  • 3
  • 11

3 Answers3

1

This is wrong if (rs2.getString(1)=="ADMIN"){ and is not working because you are comparing the references and not the content of the objects...

instead do "ADMIN".equals(rs2.getString(1)) and take a look at this post/answer if you want to learn why "==" is not the right way for comparing objects...

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • The other thing to consider is that the data in DB2 may be a fixed length character data instead of a variable length string. You may be getting back '`ADMIN '` and not `'ADMIN'`. – Charles Mar 18 '16 at 17:28
0

If you want to compare one string with another one, then always use this if other functions are always returning false:

if (rs2.getString(1).compareTo("ADMIN")==0){
                JOptionPane.showMessageDialog(null, "if statement working");
            }
-1

You can use

rs2.getString(1).equals("ADMIN")

or

"ADMIN".equals(rs2.getString(1))

The latter is better because getString might return null.

Nic
  • 6,211
  • 10
  • 46
  • 69