vb.net 检查 DataReader 中是否存在列的有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19293136/
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-09-17 15:26:26  来源:igfitidea点击:

Efficient way to check if Columns exist in the DataReader

asp.netsqlvb.net

提问by user1263981

There are tables with over 50 columns, I am using following code to loop through the dataReader for column existence.

有超过 50 列的表,我使用以下代码循环遍历 dataReader 以获取列存在。

If HasColumn(reader, "EmpCode") Then obj.OwningOfficeID = CType(reader("EmpCode"), Int32)

Protected Function HasColumn(ByRef reader As SqlDataReader, ByVal columnName As String) As Boolean
    For i As Integer = 0 To reader.FieldCount - 1
        If reader.GetName(i).Equals(columnName) Then
            Return Not IsDBNull(reader(columnName))
        End If
    Next

    Return False
End Function

I am wondering if there is any better way of checking the columns in the DataReader instead of looping through the DataReader each time i bind the object property?

我想知道是否有更好的方法来检查 DataReader 中的列而不是每次绑定对象属性时循环遍历 DataReader?

回答by Rajesh Subramanian

SqlDataReader.GetSchemaTableMethod will give the DataTable of the executed query, from there you can get all the columns

SqlDataReader.GetSchemaTable方法将给出执行查询的数据表,从那里你可以得到所有的列

Returns a DataTable that describes the column metadata.

MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getschematable.aspx

MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getschematable.aspx

回答by th1rdey3

currently I am using this extension method for this purpose

目前我正在为此目的使用此扩展方法

public static bool TryGetOrdinal(this IDataRecord dr, string column, out int ordinal)
{
    try
    {
        ordinal = dr.GetOrdinal(column);
    }
    catch(Exception ex)
    {
        ordinal = -1; //Just setting a value that GetOrdinal doesn't return
        return false;
    }
    return true;
}

so you use it as follows

所以你使用它如下

int ordinal = 0;
if(dr.TryGetOrdinal("column",out ordinal))
    string val = dr.GetValue(ordinal).ToString();

My VB is not so good. Sorry couldn't convert it to VB for you. But I think you get the basic idea and can recode it in VB.

我的VB不太好。抱歉,无法为您将其转换为 VB。但我认为您已经掌握了基本思想,并且可以在 VB 中对其进行重新编码。