DataReader:没有数据时读取的尝试无效

时间:2012-07-18 20:14:23

标签: c# asp.net sql-server database

我遇到了一些有趣的情况。我有以下代码来填充DB(ASP.net)中的字段值:

SqlConnection connect =
            new SqlConnection(
                @"conn-string"); 
SqlCommand toDo = new SqlCommand(InfoQuery, connect);
        toDo.CommandTimeout = 6000;
        connect.Open();
        using (SqlDataReader reader = toDo.ExecuteReader())
        {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    ///......retrieving some fields in the same way as below
                    foo = reader.SafeGetString(7);
                    int temp = reader.SafeGetInt32(8);
                    ///......retrieving again
                }
        }
        connect.close()

建立连接,所有参数都是正确的。在SQL Server Management Studio中,与toDo命令关联的查询非常完美。在程序中,当每个字段运行到temp值(不包括temp)时,将检索并设置。但是当读取临时值时,我得到以下异常:

  

没有数据时无效尝试读取。

这是我的扩展方法:

public static class ExtentionMethods
{
    public static string SafeGetString(this SqlDataReader reader, int colIndex)
    {
        if (!reader.IsDBNull(colIndex))
            return reader.GetString(colIndex);
        return "NULL VALUE";
    }

    public static int SafeGetInt32(this SqlDataReader reader, int colIndex)
    {
        if (!reader.IsDBNull(colIndex))
            return reader.GetInt32(colIndex);
        return -1;
    }

    public static DateTime SafeGetDateTime(this SqlDataReader reader, int colIndex)
    {
        if (!reader.IsDBNull(colIndex))
        {
            try
            {
            }
            catch
            {
                return new DateTime(1800, 1, 1);
            }
        }
        return new DateTime(1800, 1, 1);
    }
}

查询:

SELECT TOP 1000 [ID0]
        ,[Id1]
        ,[Id2]
        ,Id1+Id2+'0' AS BC
        ,[Id3]
        ,[Id4]
        ,[Id5]
        ,CAST([Date] AS nvarchar(max))
        ,[int]
        ,[Id7]
        ,[Id8]
        ,IsNull(foo,'dsf')+' '+IsNull(bar,'dsf')+', '
        +IsNull(fgm,'fggf')+', fgfggf '+IsNull(gfgf,'gfgf')+
        ','+dfsdfsdsf+', '+dsffddf AS dsadsa
        ,[fg]
        ,[fds]
        FROM tbl
        inner join tbl1 on tbl1.ID=ID1
        inner join tbl2 on tbl2.ID=ID2
        WHERE Id4=12

问题可能是什么?

1 个答案:

答案 0 :(得分:1)

我认为您不需要所有这些扩展方法,您应该按名称访问列:

while (reader.Read())
{
    int intCol = reader["MyIntColumn"] as int? ?? -1;
    string stringCol = reader["MyStringColumn"] as string ?? "NULL VALUE";
    DateTime dateCol = reader["MyDateColumn"] as DateTime? ?? new DateTime(1800, 1, 1);
}

int?DateTime?将允许空值,如果列为空,??将影响默认值。