Search code examples
mysqlsql-serverdbnull

How to use DBNull.Value to check if table column is null; return default value if not null


My current while statement is being used to get all the values from a table (two integer and one string value) and it looks like this:

                    while (reader.Read())
                {
                    Int16 a = reader.GetInt16("id");
                    **int b = (reader["nullable_id"] != DBNull.Value) ? Convert.ToInt16(reader["nullable_id"]): 0;**
                    string c = reader.GetString("string");
                    Site page = new Site(a, b, c);
                    list.Add(page);
                }

What I am using it to do is to GET all the values in a table. There's a primary key, a foreign key, and a regular string value (a, b, and c respectively). This works fine as is by allowing me to pull the primary and the string value while ignoring the foreign key that currently has null values. However, if I were to alter one of the foreign keys's value to 32 from 'null', the value won't return when I execute the GET method.

So my question is, how do I check whether or not the foreign key is null or not and then, if it is not null, it returns the value stored in the database and if it is null, then it leaves the value as null? I'm relatively new with using DBNull so I may be implementing it incorrectly.


Solution

  • simple change use this

       while (reader.Read())
                    {
                        Int16 a = Convert.ToInt16(reader["id"]);
    
                        int b = (!string.IsNullOrEmpty(Convert.ToString(reader["nullable_id"]))) ? Convert.ToInt16(reader["nullable_id"]): 0;
                        string c = Convert.ToString(reader["string"]);
                        Site page = new Site(a, b, c);
                        list.Add(page);
                    }