0

私はいくつかの興味深い状況に直面しました。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

問題は何ですか?

4

1 に答える 1

2

このすべての拡張メソッドが必要だとは思わないので、名前で列にアクセスする必要があります:

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?またはnullDateTime?を許可??し、列が null の場合はデフォルト値に影響します。

于 2012-07-20T11:15:24.953 に答える