How to insert null value in Database through parameterized query

前端 未结 3 760
独厮守ぢ
独厮守ぢ 2020-12-15 20:34

I have a datetime datatype : dttm

Also the database field type is datatime

Now I am doing this:

if (dt         


        
相关标签:
3条回答
  • 2020-12-15 21:14

    Use DBNull.Value

    if (dttm.HasValue)
    {
        cmd.Parameters.AddWithValue("@dtb", dttm);
    }
    else
    {
        cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
    }
    
    0 讨论(0)
  • 2020-12-15 21:21

    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

    0 讨论(0)
  • 2020-12-15 21:27

    if your field allows null value;

    if (dttm.HasValue)
    {
        cmd.Parameters.AddWithValue("@dtb", dttm);
    }
    else
    {
        cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
    }
    
    0 讨论(0)
提交回复
热议问题