Java - How To Check If Username Already Exists In a MySQL Table -


i want check whether username exists in database table or not.

java code:

if (e.getsource() == jbutton2) {   u = jtextfield1.gettext();   if (jtextfield1.gettext().trim().equals(""))   {     joptionpane.showmessagedialog(this, "please write username !");   }    else if (jpasswordfield1.gettext().equals(""))   {     joptionpane.showmessagedialog(this, "please write password !");   }    else   {     try {       string driver = "com.mysql.jdbc.driver";        string url = "jdbc:mysql://localhost:3306/loginform";        class.forname(driver);        connection conn = drivermanager.getconnection(url, "root", "12345");       statement s = conn.createstatement();       resultset rs = s.executequery(           "select * login username ='" + u +            "' , password ='" + jpasswordfield1.gettext() + "'");        while (rs.next()) {         string username = rs.getstring("username");         string password = rs.getstring("password");         string admin = rs.getstring("admin");          if (username.equals(u) & password.equals(jpasswordfield1.gettext()) &           admin.equals("0"))          {            joptionpane.showmessagedialog(this, "logged in !");           this.dispose();           normalusers nu = new normalusers();           break;          }          else if (username.equals(u) &            password.equals(jpasswordfield1.gettext()) & admin.equals("1"))         {            joptionpane.showmessagedialog(this,              "logged in , opening administration panel !");            this.dispose();           adminpanel ap = new adminpanel();           break;         }         else          {           joptionpane.showmessagedialog(this, "invalid username or password!");         }       }     }      catch (sqlexception | classnotfoundexception ex)     {     }   } } 

the problem that:

  • if there no rows in database, there no error message: invalid username or password.
  • when execute sql query manually: select * login see row exists there, since filter on password, doesn't while loop.

how should use java check if username exists in mysql table?

for query type specially, don't need loop through resultset.

you're trying find 1 determined record. not have 2 records same username/password (i'm assuming primary key of login table username), if(rs.next()) it's enough. if exists, validate check if it's admin.

besides, in query you're implying record must have specified username , password, no need test once result set returned.

just test user type, if it's admin, display accordingly message, else, proper.

if rs.next() not met, user doesn't exist, in else block, can display error message user not being found or being invalid.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -