即使我已经阅读了有关空值和数据库的qustions,我仍然有点困惑。我想弄清楚如何发送NULL到数据库表单C#。方法singature是将空值插入到TSQL数据库中
MyMethod(string category, int? calories, int vegetarianFriendlyMeal);
当不为空名为INT这是确定,但是当我通过空它说。
SqlCommand.Prepare方法需要的所有参数以具有明确设置类型。
请问如何让null传递给数据库,并在下面的代码中明确地设置类型?谢谢。
command.Parameters.Add("@cat", SqlDbType.VarChar, 2).Value = category;
command.Parameters.Add("@veg", SqlDbType.Int).Value = vegetarianFriendlyMeal;
if (calories == null)
{
command.Parameters.AddWithValue("@calories", DBNull.Value);
}
else
{
command.Parameters.Add("@calories", SqlDbType.Int).Value = calories;
}
我也曾尝试
SqlParameter cal = new SqlParameter("@calories", calories == null ? (object)DBNull.Value : calories);
command.Parameters.Add(cal);
具有相同的结果。
使用'.Value = calories ?? (对象)DBNull.Value;'应该工作得很好。唯一的区别是价值,那么为什么你以两种不同的方式创建参数? – Luaan
你确定这是整个代码吗?乍一看我没有看到任何问题。查询中是否有其他参数? – Andrey
@Luaan谢谢你这个作品,并保存那个if语句。 – Bendom