SqlDataReader.GetString和sqlnullvalueexception [英] SqlDataReader.GetString and sqlnullvalueexception

查看:192
本文介绍了SqlDataReader.GetString和sqlnullvalueexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的C#。我正在执行使用System.Data.SqlClient的类数据库表的一些选择查询。我sqlnullvalueexception在执行某些选择查询。在谷歌上搜索我才知道,如果值为null在数据库中,SqlDataReader.GetString(或它的变体)将抛出sqlnullvalueexception。 什么是最佳的编码做法呢?

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?

推荐答案

如果你不想重复这个有很多,只需创建一个辅助功能,如:

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

这篇关于SqlDataReader.GetString和sqlnullvalueexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆