3

I am having problem with database, creating a login screen that has 1 choice box, 1 textfield for username, 1 jpasswordfield for password. Database name-admin(username text,password text)

It's showing an error. How can I fix this.

Here is my code:

if(choice.getSelectedIndex()==1)
{
  try {
      String sql ="SELECT password FROM admin WHERE username = ? AND password = ?";
      pst = con.prepareStatement(sql);
      pst.setString(1, UserName.getText());
      /*Showing: "The method setString(int, String) in the type
        PreparedStatement is not applicable for the arguments (int, char[])*/
      pst.setString(2,passwordField.getPassword());
    }
    catch(Exception e) {
     JOptionPane.showMessageDialog(null, e);
    }
}

2 Answers 2

5

Convert the char[] array to a string before passing it to the statement:

String sql = "SELECT password FROM admin WHERE username = ? AND password = ?";
pst = con.prepareStatement(sql);
pst.setString(1, UserName.getText());
pst.setString(2, new String(passwordField.getPassword()));

If you have a look at the Javadoc, you will see that one of the String constructors in fact accepts a char[] as the input.

Sign up to request clarification or add additional context in comments.

3 Comments

If the intention is to use char[] to prevent the password from ending up in the string pool in JVM's memory, then this solution will void that intention (by creating a new String). An alternative solution would be to set a character stream on the statement, as exemplified in this aswer. This of course requires that the JDBC driver doesn't eventually create a String out of the array.
@MickMnemonic Good comment, I have never heard of this concern before. But there is an even bigger problem apparently, namely that the OP is storing cleartext passwords in the database. Instead we should be hashing the char[] and then passing this to the statement (I think).
I agree, plaintext passwords in the DB are a much bigger concern in real life scenarios.
0

You can use this:

pst.setString(2,String.valueOf(passwordField.getPassword()));

The method getPassword() returns chararray and you need a String.

Best

Comments

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.