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

标签 c# sql sql-server list

<分区>

我正在尝试构建一些查询并使用 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 的强制转换 - 您需要这样做,以便条件的两边评估为相同的类型。

关于c# - 在 C# 中向表中插入记录时无法将 NULL 值传递给参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25328529/

相关文章:

php - 在服务器上上传3张图片,并将路径保存在数据库中

mysql - 有没有办法按与其子记录关联的最早日期对父记录进行排序?

C# SqlCommand.ExecuteNonQuery 对于成功的 UPDATE SQL 语句返回 -1

c# - 测试形式仅适用于以原始类型作为参数的方法

c# - 这些静态应用程序属性是否需要锁定?

python - 使用 Python 进行 SQLite 查询

sql-server - SQL Server 使用查询计算运行总值

sql-server - 未使用的空间分配给 SQL Server 中的表

c# - 辅助功能 : Managed vs Unmanaged code

c# - 使用 ASP.NET 生成与 Visio 兼容的 XML (VDX)