SqlDataReader.GetString and sqlnullvalueexception

前端 未结 4 1170
庸人自扰
庸人自扰 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:09

    The code you posted is fine. You could also do something like that :

    value = r[n] as string;
    

    If the value in the database is null, r[n] will return DBNull.Value, and the cast to string will return null.

    0 讨论(0)
  • 2020-12-03 14:19

    This worked for me:

    value = reader.GetValue(n).ToString();
    
    0 讨论(0)
  • 2020-12-03 14:22

    That really is the best way to go about it if you wish to avoid any exceptions. You need to decide whether or not a null field represents an exceptional situation in your code - if it doesn't then use this method. If it does then I would suggest that you either allow the exception to be thrown or catch the exception and wrap it in a more meaniful exception and throw that one.

    But the main thing to know is that this is the standard way to retrieve values from a data reader when a null field does not represent an exceptional situation in the application domain.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题