在c#中,当向表插入记录时,无法将NULL值传递给参数

本文关键字:NULL 值传 参数 记录 插入 | 更新日期: 2023-09-27 18:18:05

我正在尝试构建一些查询,并使用c#将7列列表插入到SQL表中。在我的列表中,我有几个列的几个NULL值,我无法将它们传递给以下查询

string strInsertListToTable = @"INSERT INTO ImpliedOutrightData (id,product,term,bid,offer,bidcp,offercp) VALUES(@id,@product,@term,@bid,@offer,@bidcp,@offercp)";
    for (int i = 0; i < resultList.Count; i++)
        {  

           SqlCommand cmdInsertList = new SqlCommand(strInsertListToTable, sqlcon);
            cmdInsertList.CommandType = CommandType.Text;
            cmdInsertList.Parameters.Clear();
            cmdInsertList.Parameters.AddWithValue("@id", resultList[i].id);
            cmdInsertList.Parameters.AddWithValue("@product", resultList[i].product);
            cmdInsertList.Parameters.AddWithValue("@term", resultList[i].term);
            cmdInsertList.Parameters.AddWithValue("@bid", resultList[i].bid);
            cmdInsertList.Parameters.AddWithValue("@offer", resultList[i].offer);
            cmdInsertList.Parameters.AddWithValue("@bidcp",resultList[i].bidcp);
            cmdInsertList.Parameters.AddWithValue("@offercp", resultList[i].offercp);
            cmdInsertList.ExecuteNonQuery();
        }

当上述查询循环时,我得到错误

The parameterized query '(@id int,@product nvarchar(2),@term nvarchar(5),@bid float,@bidc' expects the parameter '@offercp', which was not supplied.

在c#中,当向表插入记录时,无法将NULL值传递给参数

当该参数的值为null时,应设置相应的值为DbNull.Value:

cmdInsertList.Parameters.AddWithValue(
    "@offercp"
,   resultList[i].offercp == null ? (object)DbNull.Value : resultList[i].offercp
);

注意转换为object -您需要这样做,以便条件的两边求值为相同的类型。

您需要使用DBNull.Value。我写了这个扩展方法:

public static SqlParameter AddNullSafe(this SqlParameterCollection parameters, SqlParameter value)
{
    if (value != null)
    {
        if (value.Value == null)
        {
            value.Value = DBNull.Value;
        }
        return parameters.Add(value);
    }
    return null;
}

如果您怀疑某个值可能为空,您可以使用DBNull来指示该参数的空值:

cmdInsertList.Parameters.AddWithValue("@offercp",
    resultList[i].offercp ?? DBNull.Value);