Home » Mysql » How to check for NULL in MySqlDataReader by the column's name?

How to check for NULL in MySqlDataReader by the column's name?

Posted by: admin November 30, 2017 Leave a comment

Questions:

How can I check for a NULL value in an open MySqlDataReader?

The following doesn’t work; it’s always hitting the else:

if (rdr.GetString("timeOut") == null)
{
    queryResult.Egresstime = "Logged in";
}
else
{
    queryResult.Egresstime = rdr.GetString("timeOut");
}

rdr.IsDbNull(int i) only accepts a column number, not name.

Answers:
var ordinal = rdr.GetOrdinal("timeOut");
if(rdr.IsDBNull(ordinal)) {
  queryResult.Egresstime = "Logged in";
} else {
  queryResult.Egresstime = rdr.GetString(ordinal);
}//if

or

if(Convert.IsDBNull(rdr["timeOut"])) {
  queryResult.Egresstime = "Logged in";
} else {
  queryResult.Egresstime = rdr.GetString("timeOut");
}//if

Questions:
Answers:

if(rdr.GetString(“timeOut”) == DBNull.Value)

null is not the same as DBNull

I am sorry, wrong answer, Sam B is right. I mistook this for DataRow stuff.

SqlDataReader does have strongly typed GetString() and provides IsDBNull(int column) for this case.

Questions:
Answers:

You must call rdr.IsDBNull(column) to determine if the value is DbNull.

Questions:
Answers:

Change null to DBNull.Value.

Questions:
Answers:

You can also do:

If (string.IsNullOrEmpty(rdr.GetString("timeOut"))

Questions:
Answers:

You can compare the object that retrive from NULL field with DBNull.Value.

Questions:
Answers:

Here’s one I like:

var MyString = rdr["column"] is DBNull ? "It's null!" : rdr.GetString("column");

E.g. (for the original requirement):

queryResult.Egresstime = rdr["timeOut"] is DBNull ? "Logged in" : rdr.GetString("timeOut");