Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecuteScalar() sometimes returns empty but not null object. Why?

ExecuteScalar() sometimes returns empty object -not null- although the record is exists. When I analyze this object with quickwatch, I see that object.GetType() is equal to DbNull. I can handle this empty object but I need to know why it is returns empty object sometimes although the record is exists.

string sql = @"SELECT SentDate 
               FROM dbo.EmailOut                                    
               WHERE ID = @ID";
SqlCommand cmd = new SqlCommand(sql, _cnn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@ID", ID));
object obj = cmd.ExecuteScalar();
if (obj == null)
    return false
sentDate = (DateTime)obj;
cmd.Dispose();

Most of the time my query runs perfectly. Can you please check my code?

like image 208
cihadakt Avatar asked Apr 11 '26 12:04

cihadakt


1 Answers

A return value of null means that no record was found.

A return value of DBNull means that a record was found, but the value of SentDate in that record is NULL.

like image 60
Heinzi Avatar answered Apr 19 '26 07:04

Heinzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!