title: Checking if username exists in MySQL Java
body: <p>I have a register dialog that implements an action listener. If a user enters a name and it already exists, I want to print a message on the console. If the username does not exist, MySQL should add it into the database. Unfortunately this code won't work:</p>
  
  <pre><code>private void regButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
      if(!userBox.getText().equals(""))
      {
          try
          {
              Class.forName("com.mysql.jdbc.Driver");
              Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/genx", "root", "Warlock1989");
              Statement stmt = con.createStatement();
              String query = "SELECT name FROM accounts";
              ResultSet rs = stmt.executeQuery(query);
              while(rs.next())
              {
                  String uname = rs.getString("name");
                  if(!uname.equals(userBox.getText()))
                  {
                      PreparedStatement pstmt = con.prepareStatement("INSERT INTO accounts(name) VALUES(?)");
                      pstmt.setString(1, userBox.getText());
                      pstmt.executeUpdate();
                      System.out.println("Username " + userBox.getText() + " has been registered.");
                  }
                  else
                  {
                      System.out.println("Username " + userBox.getText() + " already exists.");
                  }
              }
          }
          catch(Exception ex)
          {
              ex.printStackTrace();
          }
      } 
  </code></pre>