How to check for NULL in MySqlDataReader by the co

2019-03-18 01:34发布

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.

8条回答
爷的心禁止访问
2楼-- · 2019-03-18 02:08

Change null to DBNull.Value.

查看更多
Emotional °昔
3楼-- · 2019-03-18 02:17

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

查看更多
甜甜的少女心
4楼-- · 2019-03-18 02:19

You can also do:

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

查看更多
Viruses.
5楼-- · 2019-03-18 02:24

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");
查看更多
Luminary・发光体
6楼-- · 2019-03-18 02:28

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

查看更多
Evening l夕情丶
7楼-- · 2019-03-18 02:28

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.

查看更多
登录 后发表回答