首页 > 解决方案 > java.sql.SQLExecption:更新sql的参数索引超出范围(1>参数个数,即0)

问题描述

我的项目有问题,使用 MYSQL 对我来说还是新的,我想从数据库中获取数据并进行一些计算并更新它的值,这就像像 ATM 机一样制作提款功能。这是我的桌子的样子。 在此处输入图像描述。您可以看到带有值的构造函数参数(字符串值和字符串 ID)。对于值 =“100”;和 ID="5221311" 你可以在我的桌子图片上看到它。

public ConformWithdraw() {
    initComponents();
    try {
        Class.forName("com.jdbc.mysql.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
  public ConformWithdraw(String value,String ID) {
    initComponents();
    this.value=value;
    this.ID=ID;
  }
------------------------------------------------------------ 



private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
try {
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
    String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
                +  "'";
    PreparedStatement smtm = con.prepareStatement(validate);
    ResultSet resultSet = smtm.executeQuery();
    User user = null;

        if (resultSet.next()) {
            user = new User();
            user.setBalance(resultSet.getString("accountBalance"));
            double balance=Double.parseDouble(user.getBalance());
            double val=Double.parseDouble(value);
            total =(balance - val);
        }
        smtm.close();
        resultSet.close();
        program();


} catch (SQLException | HeadlessException | ClassCastException ex) {
        JOptionPane.showMessageDialog(null, ex);

}


 } 
-------------------------------------------------------------

 public void program(){

String sqlUpdate = "UPDATE customer_details "
            + "SET accountBalance = '"+String.valueOf(total)+"'"
            + "WHERE accountID = '"+ID+"'";
try{
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
        PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
        id=Integer.parseInt(ID);
            pstmt.setString(1, String.valueOf(total));

             pstmt.setInt(2, id);

        int rowAffected  = pstmt.executeUpdate();
    pstmt.close();
       new ShowWithdraw().setVisible(true);
       dispose();

}catch(SQLException | HeadlessException | ClassCastException ex){
    JOptionPane.showMessageDialog(null, ex);
    JOptionPane.showMessageDialog(null, "slh sini");
}

}

标签: javamysql

解决方案


您已经在查询中设置了参数,因此它尝试设置参数并且找不到要查找的参数。试试这个:

String sqlUpdate = "UPDATE customer_details "
        + "SET accountBalance = ?"
        + "WHERE accountID = ?";

推荐阅读