我正在尝试建立一些查询,并使用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
);
请注意强制转换为object
-您需要这样做,以便条件评估的双方都具有相同的类型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句