Search code examples
javamysqlsqlsqlexception

Why do I get the JavaSQLException: No value specified for parameter 1?


I am writing a code that should update the password in the database if jButton1 is pressed, but it throws the error JavaSQLException: No value specified for parameter 1. I don't get which parameter I haven't specified. Any help would be highly appreciated. Here's the code

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {          

String v0 = lbl_emp.getText();
        int x = JOptionPane.showConfirmDialog(null, "Are you sure you want to change your password?", "Update Record", JOptionPane.YES_NO_OPTION); 
        
        if(x == 0){ 
          
            try{ 

                String v1 = txt_password.getText();
                String v2 =(cmb_question.getSelectedItem().toString());
                String v3 = txt_answer.getText();
                       
                String sql = "update users set password = '"+v1+"' , secret_question = '"+v2+"', answer = '"+v3+"' where id = '"+v0+"'";
                
                if(txt_password.getText().isEmpty()){                  
                JOptionPane.showMessageDialog(txt_password, "Password field is empty");
                }
                
                else{
                pst = conn.prepareStatement(sql);
                pst.executeUpdate();
                JOptionPane.showMessageDialog(null, "Password updated");   
                }
            
            }catch(Exception e){
            
                JOptionPane.showMessageDialog(null, e);
            }  
        }
 }

Solution

  • You supply 4 Arguments to your SQL (v0 .. v3), but only specify v1, v2 and v3. A better way would also be, to use the PreparedStatement value binding, where you replace the variable values with question marks (?).

    String sql = "update users set password = ? , secret_question = ?, answer = ? where id = ?";
    ...
    PreparedStatement pst = conn.prepareStatement(sql);
    pst.setString(1, v1); // preparedStatement-Index is 1-indexed
    pst.setString(2, v2);
    pst.setString(3, v3);
    pst.setString(4, v0);
    pst.executeUpdate();
    ...
                
    

    Because, the way in which you construct your SQL makes it vulnerable to SQL-Injection-Attacks, if someone would choose a password containing escape characters for one of the parameters, i.e. using '.