Search code examples
javamysqlprepared-statementresultset

ResultSet.next() not selecting jPasswordField && jTextField


Im creating a log in page at the moment however everytime I try to "login" I get the "Your username and password dont match" message even if the Username and password are valid and stored in the database. I can't figure this out at all even from other online resources as from what I can tell it should be working?

private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) 
{                                             
    Connection con = myConnection.getConnection();
    PreparedStatement pscon;
    ResultSet rscon;

    try 
    {
        pscon = con.prepareStatement("SELECT * dbname.user WHERE 'username' = ? AND 'password' = ?");
        pscon.setString(1, jTextFieldUsername.getText());
        pscon.setString(2, String.valueOf(jPasswordFieldPass.getPassword()));
        rscon = pscon.executeQuery();

        if(rscon.next())
        {
            JOptionPane.showMessageDialog(null, "Logged in successfully!");
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Your username and password don't match!");
        }
    } 
    catch (SQLException ex) 
    {
        Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Thanks in advance for your help!


Solution

  • Your sql is write incorrect,you need to remove the redundant ' for username and password and add FROM keyword

    So change

     pscon = con.prepareStatement("SELECT * dbname.user WHERE 'username' = ? AND 'password' = ?"); 
    

    to

     pscon = con.prepareStatement("SELECT * FROM dbname.user WHERE username = ? AND password = ?");
    

    or add ` to wrap the column name

     pscon = con.prepareStatement("SELECT * FROM dbname.user WHERE `username` = ? AND `password` = ?");