SqlDataReader.GetString and sqlnullvalueexception

前端 未结 4 1186
庸人自扰
庸人自扰 2020-12-03 13:38

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.

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 14:24

    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);
    

提交回复
热议问题