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

必须

我正在尝试建立一些查询,并使用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.
谢尔盖·卡里尼琴科(Sergey Kalinichenko)

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

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

请注意强制转换为object-您需要这样做,以便条件评估的双方都具有相同的类型。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将参数传递给函数时在oracle中返回null?

在c#中执行Powershell脚本文本,将值传递给Param节中的参数

从C#将表类型对象作为输入参数传递给Oracle中的存储过程

我无法将数组作为参数传递给 C# 中的函数

在 C++ 中嵌入 Python 时无法将参数传递给 Python 函数

将参数传递给 C# 中的存储过程时出错

在初始化C#时将参数传递给字典中的操作

什么是将30个以上的参数值传递给存储过程以在表中插入值的更好方法?

将参数传递给C#中的工厂模式架构

将枚举作为参数传递给 C# 中的方法

将记录插入到Cassandra表中

C#将参数传递给Lambda

c#将参数传递给Action

将参数从C#传递给Python

C#将参数传递给委托

将值传递给脚本中的参数

当参数为NULL时将DEFAULT值插入列中

在将值类型传递给C#中的方法时进行更改

“无法将值NULL插入列...” SqlException,同时将哈希值插入到列中

SQL错误:将表参数传递给表值函数时,“必须声明标量变量”

将指针的值复制到变量,将指针作为参数传递给C程序

无法将列名从插入到表中

有没有办法将参数作为插入到 sql 表的值传递?

无法将子接口作为C#中的参数传递

将值传递给表值参数时忽略身份列

如何将值收集到数组中并将集合传递给C#中的datagridview?

将数组传递给sql并将其插入一个值的链接表中

无法将参数传递给jar启动器到shell脚本中

MVC C#将参数传递给VIA ActionLink到控制器