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

左心房为你撑大大i 提交于 2019-12-20 17:33:04

问题


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.


回答1:


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



回答2:


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.




回答3:


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




回答4:


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




回答5:


Change null to DBNull.Value.




回答6:


You can also do:

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




回答7:


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");



回答8:


Here is a method that I created to read DBNull and return a default(T) incase:

   private T GetNullable<T>(MySqlDataReader reader, int ordinal, Func<int, T> getValue)
        {
            if (reader.IsDBNull(ordinal))
            {
                return default(T);
            }
            return getValue(ordinal);
        }

It can be used like this:

   if (reader.Read())
            {
                account = new Account();
                account.Id = reader.GetInt32(0);
                account.Name = reader.GetString(1);
                account.MailVerifiedAt = GetNullable(reader, 2, reader.GetDateTime);
                account.MailToken = GetNullable(reader, 3, reader.GetString);
            }

The generic type T will be resolved based on the return value of the reader.- method. If it returns a string you will receive a null incase of DBNull. If it is an int it will return 0, etc.

Note: for integer values it might not be desired to get a 0 so be careful.



来源:https://stackoverflow.com/questions/4739641/how-to-check-for-null-in-mysqldatareader-by-the-columns-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!