How to insert null value in Database through parameterized query

你。 提交于 2019-11-27 21:40:33

问题


I have a datetime datatype : 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.


回答1:


Use DBNull.Value

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



回答2:


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

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

This will eliminate the need for the if statment




回答3:


if your field allows null value;

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


来源:https://stackoverflow.com/questions/16717179/how-to-insert-null-value-in-database-through-parameterized-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!