如何通过参数化查询在数据库中插入空值

时间:2022-03-02 13:12:01

I have a datetime datatype : dttm

我有一个datetime数据类型:dttm

Also the database field type is datatime

数据库字段类型也是数据时间

Now I am doing this:

现在我这样做:

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    // It should insert null value into database
    // through cmd.Parameters.AddWithValue("@dtb", _____)
}

How can this be done.

如何才能做到这一点。

3 个解决方案

#1


18  

Use DBNull.Value

使用DBNull.Value

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
}

#2


29  

This can be done using the null-coalescing operator: if the value of dttm is null the DBNull.Value will be inserted otherwise the value of dttm will be used

这可以使用null-coalescing运算符来完成:如果dttm的值为null,则将插入DBNull.Value,否则将使用dttm的值

cmd.Parameters.AddWithValue("@dtb", dttm ?? (object) DBNull.Value);

This will eliminate the need for the if statment

这将消除对if语句的需要

#3


3  

if your field allows null value;

如果你的字段允许空值;

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
}

#1


18  

Use DBNull.Value

使用DBNull.Value

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
}

#2


29  

This can be done using the null-coalescing operator: if the value of dttm is null the DBNull.Value will be inserted otherwise the value of dttm will be used

这可以使用null-coalescing运算符来完成:如果dttm的值为null,则将插入DBNull.Value,否则将使用dttm的值

cmd.Parameters.AddWithValue("@dtb", dttm ?? (object) DBNull.Value);

This will eliminate the need for the if statment

这将消除对if语句的需要

#3


3  

if your field allows null value;

如果你的字段允许空值;

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
}