Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 684
rd42 Avatar asked Jan 19 '11 19:01

rd42


People also ask

How check Datareader is null?

Try this way: stirng query = "SELECT ColumnA FROM MyTable WHERE ColumnB = 'some condition'"; //... initialize connection and command and reader classes //then do: if(reader. Read()) //if there are any value(s) { if(reader. GetValue(0) !=

How do I find null records in mysql?

To look for NULL values, you must use the IS NULL test. The following statements show how to find the NULL phone number and the empty phone number: mysql> SELECT * FROM my_table WHERE phone IS NULL; mysql> SELECT * FROM my_table WHERE phone = ''; See Section 3.3.

How does ado net handle null value?

For working with database ANSI SQL null values, use System. Data. SqlTypes nulls rather than Nullable. For more information on working with CLR value nullable types in Visual Basic see Nullable Value Types, and for C# see Nullable value types.

How do you handle database NULL values in C#?

IsNullOrEmpty() Method of C# If any string is not assigned any value, then it will have Null value. The symbol of assigning Null value is “ “or String. Empty(A constant for empty strings). This method will take a parameter that will be of System.


2 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
like image 77
Viacheslav Ivanov Avatar answered Oct 07 '22 14:10

Viacheslav Ivanov


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.

like image 29
Axarydax Avatar answered Oct 07 '22 12:10

Axarydax