使用 Repeater 命令参数更新数据库时出现无效的列名 userId 错误

Invalid column name userId error occur while updating database using Repeater Command Argument

这是Asp.net按钮代码

<asp:Button ID="Button2" runat="server" Text="Approved Job Request" CssClass="css_button" CommandName="ApplyButton" CommandArgument='<%#Eval("AId")%>' />

这是 C# 代码

 if (e.CommandName == "ApplyButton")
    {
        int userId = int.Parse(e.CommandArgument.ToString());

        SqlConnection con = new SqlConnection("Data Source=Mrunal;Initial Catalog=JobPortalDB;Integrated Security=True");

        String sql = "update AppliedJob set AApprove='yes' where AId=userId";
        SqlCommand cmd = new SqlCommand(sql,con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        Response.Redirect("~/ReqHome.aspx");
    }

使用上面的代码,出现错误

System.Data.SqlClient.SqlException: Invalid column name 'userId'

。 怎么办?

因为你在更新子句中的条件不正确

你可以这样做:

 String sql = "update AppliedJob set AApprove='yes' where AId='"+userId+"'";

但是以上不是SQL注入的动力,我不推荐使用SQL参数所以 试试这个:

 int userId = int.Parse(e.CommandArgument.ToString());
 String sql = "update AppliedJob set AApprove='yes' where AId=@userId";
 SqlCommand cmd = new SqlCommand(sql,con);
 cmd.Parameters.AddWithValue("@userId", userId);