绑定 SQL 参数时“必须声明标量变量'@x'”

本文关键字:变量 标量 声明 参数 SQL 绑定 | 更新日期: 2023-09-27 17:56:24

我在Visual Studio中得到错误是"必须声明标量变量'@PhNo',我猜不出我在哪里拼写错误。我希望这将清除我的错误,提前谢谢。:) :)

C# 代码:

string Name = Session["Username"].ToString();
con.Open();
SqlCommand Update_cmd = new SqlCommand("Update RegisterUser set FullName = @Name, PhoneNo = @PhNo ,EmailId = @ID WHERE UserName = '"+Name+"'", con);
Update_cmd.Parameters.AddWithValue("@Name",txtFullName.Text);
Update_cmd.Parameters.AddWithValue("@PhNo",txtPhNo.Text);
Update_cmd.Parameters.AddWithValue("@ID", txtMailID.Text);
Update_cmd.ExecuteNonQuery();
lblResultMsg.Text = "Your Profile has been successfully saved";
con.Close();

绑定 SQL 参数时“必须声明标量变量'@x'”

            using (SqlConnection con = new SqlConnection(_connectionString))
            {
                string qry = @"UPDATE dbo.RegisterUser SET FullName = @Name, PhoneNo = @PhNo, EmailId = @EID FROM dbo.RegisterUser WHERE UserName = @Name";
                using (SqlCommand cmd = new SqlCommand(qry, con))
                {
                    cmd.Parameters.AddWithValue("@Name", SqlDbType.NVarChar).Value = txtFullName.Text;
                    cmd.Parameters.AddWithValue("@PhNo", SqlDbType.NVarChar).Value = txtPhNo.Text;
                    cmd.Parameters.AddWithValue("@EID", SqlDbType.Int).Value = (int)txtMailID.Text;
                    cmd.CommandType = CommandType.Text;
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
            };

还可以考虑使用 Prepare 方法来执行 sql 语句。