Note that there are some explanatory texts on larger screens.

plurals
  1. POJava - How To Check If Username Already Exists In a MySQL Table
    text
    copied!<p>I want to check whether a <code>username</code> already exists in a <code>database</code> table or not.</p> <p><strong>Java Code:</strong></p> <pre><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 * FROM login where username ='" + U + "' and 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) &amp; Password.equals(jPasswordField1.getText()) &amp; Admin.equals("0")) { JOptionPane.showMessageDialog(this, "Logged In Successfully !"); this.dispose(); NormalUsers NU = new NormalUsers(); break; } else if (Username.equals(U) &amp; Password.equals(jPasswordField1.getText()) &amp; Admin.equals("1")) { JOptionPane.showMessageDialog(this, "Logged In Successfully , Opening Administration Panel !"); this.dispose(); AdminPanel AP = new AdminPanel(); break; } else { JOptionPane.showMessageDialog(this, "Invalid Username Or Password!"); } } } catch (SQLException | ClassNotFoundException ex) { } } } </code></pre> <p><strong>The problem is that:</strong></p> <ul> <li>If there are no rows in the <code>database</code>, then there is no an error message: <code>Invalid Username or Password</code>. </li> <li>When I execute the <code>SQL</code> query manually: <code>SELECT * From Login</code> I see the row exists there, but since I filter on <code>password</code>, it doesn't get into the <code>while loop</code>.</li> </ul> <p><strong>How should I use java to check if a username exists in a MySQL table?</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload