Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Data Reader - handling Null column values

I'm using a SQLdatareader to build POCOs from a database. The code works except when it encounters a null value in the database. For example, if the FirstName column in the database contains a null value, an exception is thrown.

employee.FirstName = sqlreader.GetString(indexFirstName); 

What is the best way to handle null values in this situation?

like image 690
DenaliHardtail Avatar asked Nov 20 '09 17:11

DenaliHardtail


People also ask

What ignores NULL values in SQL?

To exclude the null values from the table we need to use IS NOT NULL operator with the WHERE clause. WHERE Clause: The WHERE clause is used to filter the records. It will extract those records that fulfill the condition.

Does SQL allow NULL values?

Using NULL values in your database is a permanent choice. Once you choose to allow them, you need to allow NULLs in all SQL database tables. Relational databases include NULLs by default, but they all let you reject NULLs should you decide to require developers to enter a value.


1 Answers

You need to check for IsDBNull:

if(!SqlReader.IsDBNull(indexFirstName)) {   employee.FirstName = sqlreader.GetString(indexFirstName); } 

That's your only reliable way to detect and handle this situation.

I wrapped those things into extension methods and tend to return a default value if the column is indeed null:

public static string SafeGetString(this SqlDataReader reader, int colIndex) {    if(!reader.IsDBNull(colIndex))        return reader.GetString(colIndex);    return string.Empty; } 

Now you can call it like this:

employee.FirstName = SqlReader.SafeGetString(indexFirstName); 

and you'll never have to worry about an exception or a null value again.

like image 51
marc_s Avatar answered Oct 09 '22 02:10

marc_s