参数化查询'(@ username nvarchar(4000))DELETE FROM Staff WHERE Username = @ user'需要参数' @ username',这是未提供的

时间:2016-12-20 17:54:29

标签: c# sql sql-server visual-studio

我的代码出现问题:

public partial class DeleteStaff : System.Web.UI.Page
{
    string username = null;
    SqlConnection conn = null;
    SqlCommand cmd = null;
    string connectionString = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        // if loading the page for the first time
        if (!IsPostBack)
        {
            // Check that there is an id passed in with the QueryString
            if (Request.Params["username"] != null)
            {
                // retrieve the id
                username = Convert.ToString(Request.Params["username"]);
            }

            // retrieve connectionString from Web.Config file
            connectionString = ConfigurationManager.ConnectionStrings["LMSCS"].ConnectionString;

            // create connection with database specified in the connectionString
            conn = new SqlConnection(connectionString);

            // prepare sql statement
            string sql = "DELETE FROM Staff WHERE Username=@username";

            try
            {    
                // create SqlCommand object with sql statement and connection
                cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@username", username);

                // Open database connection
                conn.Open();

                // Execute SqlCommand
                int rows = cmd.ExecuteNonQuery();

                if (rows > 0)
                {
                    lblOutput.Text = "Record deleted successfully.";
                }
                else
                {
                    lblOutput.Text = "Record cannot be deleted.";
                }
            }
            catch (Exception ex)
            {
                lblOutput.Text = "Error Message: " + ex.Message;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
    }
}

一旦我按下删除但是对于特定项目,我收到此错误:

  

参数化查询'(@ username nvarchar(4000))DELETE FROM Staff WHERE Username = @ user'需要参数' @ username',这是未提供的。

3 个答案:

答案 0 :(得分:0)

使用Add方法并定义参数类型,而不是AddWithValue方法。似乎AddWithValue正在猜测类型(nvarchar(4000))。 AddWithValue只接受一个对象,因此参数数据类型没有正确映射。

示例from MSDN

    command.Parameters.Add("@ID", SqlDbType.Int);
    command.Parameters["@ID"].Value = customerID;

答案 1 :(得分:0)

我认为当username == null时会发生错误。在这种情况下,不会添加参数(DBNULL.Value和null不同)。 最好先检查输入参数

if (Request.Params["username"] == null) throw ...

答案 2 :(得分:0)

用户名是您应该传递到数据库的字符串。