Django Anonymous
Django Anonymous

Reputation: 3025

How to insert null value in Database through parameterized query

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.

Upvotes: 22

Views: 19129

Answers (3)

Kevin Kunderman
Kevin Kunderman

Reputation: 2134

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

Upvotes: 47

Carlos Landeras
Carlos Landeras

Reputation: 11063

Use DBNull.Value

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

Upvotes: 22

Furkan Ekinci
Furkan Ekinci

Reputation: 2632

if your field allows null value;

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

Upvotes: 4

Related Questions