Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlDataReader.GetString and sqlnullvalueexception

Tags:

c#

.net

I am new to C#. I was executing some select queries from database tables using System.Data.SqlClient classes. I got sqlnullvalueexception while executing some select query. On googling I come to know that if the value is null in the database, SqlDataReader.GetString (or it's variants) will throw sqlnullvalueexception. What is the best coding practice for this?

if (!sqlDataReader.IsDBNull(n)) value = r.GetString(n); 

Any better way of coding?

like image 902
Rejeev Divakaran Avatar asked Aug 03 '09 12:08

Rejeev Divakaran


People also ask

Is there anything faster than Sqldatareader in net?

Caching namespace. If you're doing purely data operations (as your question suggests), you could rewrite your code which is using the data to be T-SQL and run natively on SQL. This has the potential to be much faster, as you will be working with the data directly and not shifting it about.

How do I check if a Datareader has a column?

string ColumnValue; if (dr["ColumnName"] != null) ColumnValue = dr["ColumnName"].

How do you handle database NULL values in C#?

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.


1 Answers

If you don't want to repeat this a lot, just create a helper function, like this:

public static class DataReaderExtensions {     public static string GetStringOrNull(this IDataReader reader, int ordinal)     {         return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);     }      public static string GetStringOrNull(this IDataReader reader, string columnName)     {         return reader.GetStringOrNull(reader.GetOrdinal(columnName));     } } 

Which you can call like this:

value = reader.GetStringOrNull(n); 
like image 70
Tommy Carlier Avatar answered Oct 13 '22 19:10

Tommy Carlier