参数化查询.....期望参数'@units',这是未提供的

时间:2014-05-03 18:34:41

标签: c# sql-server exception

我得到了这个例外:

  

参数化查询'(@ Name nvarchar(8),@ type nvarchar(8),@ units nvarchar(4000),@ rang'需要参数' @ units',没有提供。

我的插入代码是:

public int insertType(string name, string type, string units = "N\\A", string range = "N\\A", string scale = "N\\A", string description = "N\\A", Guid guid = new Guid())
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand();
        command.CommandText = "INSERT INTO Type(name, type, units, range, scale, description, guid) OUTPUT INSERTED.ID VALUES (@Name, @type, @units, @range, @scale, @description, @guid) ";
        command.Connection = connection;
        command.Parameters.AddWithValue("@Name", name);
        command.Parameters.AddWithValue("@type", type);
        command.Parameters.AddWithValue("@units", units);
        command.Parameters.AddWithValue("@range", range);
        command.Parameters.AddWithValue("@scale", scale);
        command.Parameters.AddWithValue("@description", description);
        command.Parameters.AddWithValue("@guid", guid);
        return (int)command.ExecuteScalar();
    }
}

异常是一个惊喜,因为我使用AddWithValue函数并确保为函数添加了默认参数。

解决:

问题在于一些参数所在的空字符串(覆盖默认值)

这是工作代码:

public int insertType(string name, string type, string units = "N\\A", string range = "N\\A", string scale = "N\\A", string description = "N\\A", Guid guid = new Guid())
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlCommand command = new SqlCommand();
            command.CommandText = "INSERT INTO Type(name, type, units, range, scale, description, guid) OUTPUT INSERTED.ID VALUES (@Name, @type, @units, @range, @scale, @description, @guid) ";
            command.Connection = connection;
            command.Parameters.AddWithValue("@Name", name);
            command.Parameters.AddWithValue("@type", type);

            if (String.IsNullOrEmpty(units))
            {
                command.Parameters.AddWithValue("@units", DBNull.Value); 
            }
            else
                command.Parameters.AddWithValue("@units", units);
            if (String.IsNullOrEmpty(range))
            {
                command.Parameters.AddWithValue("@range", DBNull.Value);
            }
            else
                command.Parameters.AddWithValue("@range", range);
            if (String.IsNullOrEmpty(scale))
            {
                command.Parameters.AddWithValue("@scale", DBNull.Value);
            }
            else
                command.Parameters.AddWithValue("@scale", scale);
            if (String.IsNullOrEmpty(description))
            {
                command.Parameters.AddWithValue("@description", DBNull.Value);
            }
            else
                command.Parameters.AddWithValue("@description", description);




            command.Parameters.AddWithValue("@guid", guid);


            return (int)command.ExecuteScalar();
        }


    }

5 个答案:

答案 0 :(得分:74)

试试这段代码:

SqlParameter unitsParam = command.Parameters.AddWithValue("@units", units);
if (units == null)
{
    unitsParam.Value = DBNull.Value;
}

您必须检查所有其他参数的空值。如果为null,则必须传递DBNull.Value值。

答案 1 :(得分:24)

以下是使用null-coalescing运算符的方法:

cmd.Parameters.AddWithValue("@units", units ?? (object)DBNull.Value);
cmd.Parameters.AddWithValue("@range", range ?? (object)DBNull.Value);
cmd.Parameters.AddWithValue("@scale", scale ?? (object)DBNull.Value);
cmd.Parameters.AddWithValue("@description", description ?? (object)DBNull.Value);

或者更严格的类型检查:

cmd.Parameters.Add("@units", SqlDbType.Int).Value = units ?? (object)DBNull.Value;
cmd.Parameters.Add("@range", SqlDbType.Int).Value = range ?? (object)DBNull.Value;
cmd.Parameters.Add("@scale", SqlDbType.Int).Value = scale ?? (object)DBNull.Value;
cmd.Parameters.Add("@description", SqlDbType.VarChar).Value = description ?? (object)DBNull.Value;

操作员也被链接:

int?[] a = { null, null, 1 };
Console.WriteLine(a[0] ?? a[1] ?? a[2]);

答案 2 :(得分:1)

command.Parameters.AddWithValue(" @ Name",(name == null?"":name));

答案 3 :(得分:0)

这是一个可以重复使用多个参数的方法:

    public void NullorEmptyParameter(QC.SqlCommand command, string at, string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            command.Parameters.AddWithValue(at, DBNull.Value);
        }
        else
            command.Parameters.AddWithValue(at, value);
    }

然后你可以将它重用于尽可能多的命令和参数:

    NullorEmptyParameter(command, "@Idea_ID", Idea_ID);
    NullorEmptyParameter(command, "@Opportunities_or_Idea", Opportunities_or_Idea);

答案 4 :(得分:0)

到目前为止,对于这些问题,该扩展类对我有用两次:

public static class DbValueExtensions
{
    // Used to convert values coming from the db
    public static T As<T>(this object source)
    {
        return source == null || source == DBNull.Value
            ? default(T)
            : (T)source;
    }

    // Used to convert values going to the db
    public static object AsDbValue(this object source)
    {
        return source ?? DBNull.Value;
    }
}

您通常会在两种情况下使用它。首先,在为查询创建参数时:

var parameters = new Dictionary<string, object>
{
    { "@username", username.AsDbValue() },
    { "@password", password.AsDbValue() },
    { "@birthDate", birthDate.AsDbValue() },
};

或在解析SqlReader值时:

while (reader.Read())
{
    yield return new UserInfo(
        reader["username"].As<string>(),
        reader["birthDate"].As<DateTime>(),
        reader["graduationDate"].As<DateTime?>(),
        reader["nickname"].As<string>()
    );
}