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.
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) !=
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With