0

Hi i current have a query that I'm trying to run however every time i try to run this query i get an array index out of bounds, I'm not sure why this is as i have not declared any arrays in my code, can anyone help?

public void actionPerformed(ActionEvent argO) {

    try{
        String query="select * from Users where Username ='admin' and password='password2'  ";
        PreparedStatement pst=connection.prepareStatement(query);
        pst.setString(1, text_username.getText());
        pst.setString(2, passwordField.getText());

        ResultSet rs=pst.executeQuery();
        int count=0;
        while(rs.next())
        {
            count=count+1;

        }
        if(count==1)
        {
            JOptionPane.showMessageDialog(null, "Username and password is correct");
            frmMychatApp.dispose();
            AdminPage admin = new AdminPage();
            admin.setVisible(true);
        }
        else if(count>1)
        {
            JOptionPane.showMessageDialog(null, "Duplicate Username and password");
        }
        else{
            JOptionPane.showConfirmDialog(null, "Username and password is not correct. Please Try Again");
        }

        rs.close();
        pst.close();
    }catch (Exception e)
    {
        JOptionPane.showMessageDialog(null, e);
        e.printStackTrace();
    }

1 Answer 1

2

The exception is being thrown because there are no placeholders for the parameters to be filled in the query. You should use ? characters instead of the hardcoded values:

String query="select * from Users where Username =? and password=?  ";
PreparedStatement pst=connection.prepareStatement(query);
pst.setString(1, text_username.getText());
pst.setString(2, passwordField.getText());
Sign up to request clarification or add additional context in comments.

1 Comment

You are correct but what I'm try to achieve is to have the try block execute the line of code when the username='admin' and the password='password'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.