准备好的陈述错误

时间:2013-12-02 13:47:51

标签: netbeans

我有错误。 当我运行该文件时,它被声明 “INFO:SQL异常命中:参数索引超出范围(2>参数数量,即0)。”

PreparedStatement pst = conn.prepareStatement(
          "UPDATE Customers SET Contact = " + contact_num + "," 
          + "Email = '" + email_add + "'," 
          + "Address = '" + mail_add + "'," 
          + "SurveyStatus = " + radio_group + ","
          + "Subscription = " + receive_info + " " 
  + "WHERE MembershipID = '" + member_ID + "' " );

          pst.setString(2,contact_num);
          pst.setString(3,email_add);
          pst.setString(4,mail_add);
          pst.setString(5,radio_group);
          pst.setString(6,receive_info);
          pst.setString(1,member_ID);

           stmt.executeUpdate(strSqlnsert);
            pst.executeUpdate(strSqlUpdate);

我有另外一个错误,声明语法错误

"INSERT INTO Customers(MembershipID,Contact,Email,Address,SurveyStatus,Subscription) VALUES"
  + "?" + "," + "?" + "," + "?" + "," + "?" + "," + "?" + "," + "?");

2 个答案:

答案 0 :(得分:1)

PreparedStatement中,使用不带引号的?字符来表示参数替换。

PreparedStatement pst = conn.prepareStatement(
      "UPDATE Customers SET Contact = ?," 
      + "Email = ?," 
      + "Address = ?," 
      + "SurveyStatus = ?,"
      + "Subscription = ? " 
      + "WHERE MembershipID = ? " );

你通过直接替换值来击败PreparedStatement的目的。那么您的pst.setString()来电是没有意义的,因为没有任何?要替换。

出现错误消息,因为解析器正在计算?,并且找到零。当你第一次感到恐慌时.setString()

另请注意,您需要更改.setString()来电中的索引。 member_ID是最后一个?,所以它应该是数字6,其他索引应该相应调整。

答案 1 :(得分:0)

写下你准备好的陈述:

PreparedStatement pst =      conn.prepareStatement( "UPDATE Customers SET   Contact =?,  Email = ?, Address = ?,SurveyStatus =?,Subscription =? WHERE MembershipID =?" );