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?
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.
string ColumnValue; if (dr["ColumnName"] != null) ColumnValue = dr["ColumnName"].
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With