参数化查询需要'@firstname nvarchar,@lastname nvarchar,@phone nvarchar需要参数@email,但没有提供

ilmyapht  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(338)

这个问题在这里已经有答案了

参数化查询…需要未提供的参数'@units'(5个答案)
9个月前关门了。
有没有什么大师能帮我解决这个问题?我一直在c#中抛出这个异常,但是我看到的一切似乎都是正确的。这是密码

public bool Insert(loginBLL u)
    {
        bool isSuccess = false;
        SqlConnection conn = new SqlConnection(myconnstrng);

        try
        {
            String sql = "INSERT INTO customers (firstname, lastname, phone, email, address, city, state, zipcode, password, username) VALUES (@firstname, @lastname, @phone, @email, @address, @city, @state, @zipcode, @password, @username)";
            SqlCommand cmd = new SqlCommand(sql, conn);

            cmd.Parameters.AddWithValue("@firstname", u.firstname);
            cmd.Parameters.AddWithValue("@lastname", u.lastname);
            cmd.Parameters.AddWithValue("@phone", u.phone);
            cmd.Parameters.AddWithValue("@email", u.email);
            cmd.Parameters.AddWithValue("@address", u.address);
            cmd.Parameters.AddWithValue("@city", u.city);
            cmd.Parameters.AddWithValue("@state", u.state);
            cmd.Parameters.AddWithValue("@zipcode", u.zipcode);
            cmd.Parameters.AddWithValue("@password", u.password);
            cmd.Parameters.AddWithValue("@username", u.username);

            conn.Open();

            int rows = cmd.ExecuteNonQuery();
zphenhs4

zphenhs41#

我怀疑你的问题是因为传球 (object)null 而不是 DBNull.Value 对于空参数。
现在,我会通过编写一个扩展方法来绑定 FormattableString .

public static SqlCommand GetCommandInterpolated(this SqlConnection conn, FormattableString sql)
        {
            var cmd = conn.CreateCommand();
            var replacements = new string[sql.ArgumentCount];
            var args = sql.GetArguments();

            for (int i = 0; i < sql.ArgumentCount; i++)
            {
                var p = cmd.CreateParameter();
                cmd.Parameters.Add(p);
                p.ParameterName = replacements[i] = $"@p_{i}";
                p.Value = args[i] ?? DBNull.Value;
            }
            cmd.CommandText = string.Format(sql.Format, replacements);
            return cmd;
        }

        var cmd = conn.GetCommandInterpolated(
            $@"INSERT INTO customers (firstname, lastname, phone, email, address, city, state, zipcode, password, username)
            VALUES ({u.firstname}, {u.lastname}, {u.phone}, {u.email}, {u.address}, {u.city}, {u.state}, {u.zipcode}, {u.password}, {u.username}"
        );

相关问题