C# SqlDataReader.GetString 和 sqlnullvalueexception

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1222116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:50:03  来源:igfitidea点击:

SqlDataReader.GetString and sqlnullvalueexception

c#.net

提问by Rejeev Divakaran

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?

我是 C# 的新手。我正在使用 System.Data.SqlClient 类从数据库表中执行一些选择查询。我在执行一些选择查询时遇到了 sqlnullvalueexception。在谷歌搜索中,我知道如果数据库中的值为 null,SqlDataReader.GetString(或其变体)将抛出 sqlnullvalueexception。最好的编码实践是什么?

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

Any better way of coding?

有没有更好的编码方式?

采纳答案by Tommy Carlier

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

回答by Andrew Hare

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.

如果您希望避免任何异常,那确实是最好的方法。您需要确定 null 字段是否表示代码中的异常情况 - 如果没有,则使用此方法。如果是这样,那么我建议您要么允许抛出异常,要么捕获异常并将其包装在一个更有意义的异常中并抛出该异常。

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.

但要知道的主要事情是,当空字段不代表应用程序域中的异常情况时,这是从数据读取器检索值的标准方法。

回答by Thomas Levesque

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 stringwill return null.

如果数据库中的值为空,r[n]将返回 DBNull.Value,并且强制转换string将返回null

回答by drzymala

This worked for me:

这对我有用:

value = reader.GetValue(n).ToString();