3

I am trying to check if the username already exists in the table: The database also has the field set to unique The method will return a boolean stating if the username already exists or not. The part of my code that sets the usernameExists var to true never runs even if the usernames are the same.

 public static boolean CheckUsernameExists(String username)
{
    boolean usernameExists = false;

    try
    {

        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(urlDB, usernameDB, passwordDB);

        PreparedStatement st = connection.prepareStatement("select * from Members order by username desc");
        ResultSet r1=st.executeQuery();
        String usernameCounter;
         if(r1.next()) 
         {
           usernameCounter =  r1.getString("username");
           if(usernameCounter == username) //this part does not happen even if it should
           {
               System.out.println("It already exists");
              usernameExists = true;
           }
         }


     }

     catch (SQLException e) 
     {
        System.out.println("SQL Exception: "+ e.toString());
     } 
     catch (ClassNotFoundException cE) 
     {
        System.out.println("Class Not Found Exception: "+ cE.toString());
     }

 return usernameExists;
 }

IF you can help in anyway I would be thankful!

user3211740
  • 175
  • 3
  • 6
  • 12

4 Answers4

2

Use if(usernameCounter.equals(username)). String comparisons are tricky. This has been discussed in detail here.

Community
  • 1
  • 1
Sujith Surendranathan
  • 2,569
  • 17
  • 21
2

Never compare two String instances using ==, use equals() (== checks for identity, not equality).

You could also directly use the username in the query, rather than taking the username from the query result:

PreparedStatement st = connection.prepareStatement("select * from Members where username = ?");
st.setString(1, username);
ResultSet r1=st.executeQuery();
if(r1.next()) {
  usernameExists = true;
}
EmirCalabuch
  • 4,756
  • 1
  • 25
  • 20
2

As everyone has pointed out, you need to use .equals when you compare strings. however for your usage, I would recommend using .equalsIgnoreCase, as you probably want it to treat "MSmith" and "msmith" as the same.

Also, a much more efficient way to perform this check would be to select the row on the table

PreparedStatement st = connection.prepareStatement("select * from Members username=?");
st.setString(1,username);

Then, if you get a row, you know the username is already used. If you don't get a row or you get a RowNotFoundException, then you can treat that as "the username has not been used". Again, you would need to be careful with the case of the input when doing the check.

M21B8
  • 1,867
  • 10
  • 20
0

Your problem is usernameCounter == username. You are comparing objects where instead I think you want to be comparing strings.

try usernamecounter.equals(username)

user3229382
  • 81
  • 1
  • 4