好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

在C#中将记录插入表时无法将NULL值传递给参数

参见英文答案 > The parameterized query expects the parameter which was not supplied                                    6个

我正在尝试构建一些查询并使用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.
当参数的值为null时,应将相应的值设置为DbNull.Value:

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

注意转换为对象 – 您需要这样,以便条件的两边评估为相同的类型.

查看更多关于在C#中将记录插入表时无法将NULL值传递给参数的详细内容...

  阅读:85次