【问题标题】:Why do I get the JavaSQLException: No value specified for parameter 1?为什么我会收到 JavaSQLException: No value specified for parameter 1?
【发布时间】:2021-03-11 05:07:23
【问题描述】:

我正在编写一个代码,如果按下 jButton1,它应该更新数据库中的密码,但它会抛出错误 JavaSQLException: No value specified for parameter 1。我没有得到我没有指定的参数。任何帮助将不胜感激。这是代码

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);
            }  
        }
 }

【问题讨论】:

  • txt_passwordJPasswordField 组件吗?如果是,则不能使用:txt_password.getText()。应该是:String v0 = String.valueOf(txt_password.getPassword());.
  • 谢谢@DevilsHnd,我已经改好了

标签: java mysql sql sqlexception


【解决方案1】:

您为 SQL (v0 .. v3) 提供 4 个参数,但仅指定 v1、v2 和 v3。还有一种更好的方法是使用 PreparedStatement 值绑定,将变量值替换为问号 (?)。

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();
...
            

因为,如果有人为其中一个参数选择包含转义字符的密码,即使用',那么构建 SQL 的方式使其容易受到 SQL 注入攻击。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    相关资源
    最近更新 更多