检查数据读取器中是否存在列

发布于 2024-07-29 20:59:20 字数 500 浏览 16 评论 0原文

有没有一种方法可以查看基于 IDataReader 的对象中是否存在字段,而无需检查 IndexOutOfRangeException?

本质上,我有一个方法,它采用基于 IDataReader 的对象并创建强类型的记录列表。 在一种情况下,一个数据读取器具有其他读取器没有的字段。 如果不需要的话,我真的不想重写提供此方法的所有查询以包含此字段的某种形式。 到目前为止,我能够弄清楚如何做到这一点的唯一方法是将 1 个唯一字段放入 try/catch 块中,如下所示。

try
{
    tmp.OptionalField = reader["optionalfield"].ToString();
}
catch (IndexOutOfRangeException ex)
{
    //do nothing
}

除了将“可选字段”添加到其他查询或复制加载方法之外,是否有一种更干净的方法,以便一个版本使用可选字段而另一个版本不使用?

我也是2.0框架。

Is there a way to see if a field exists in an IDataReader-based object w/o just checking for an IndexOutOfRangeException?

In essence, I have a method that takes an IDataReader-based object and creates a strongly-typed list of the records. In 1 instance, one data reader has a field that others do not. I don't really want to rewrite all of the queries that feed this method to include some form of this field if I don't have to. The only way I have been able to figure out how to do it so far is to throw the 1 unique field into a try/catch block as shown below.

try
{
    tmp.OptionalField = reader["optionalfield"].ToString();
}
catch (IndexOutOfRangeException ex)
{
    //do nothing
}

Is there a cleaner way short of adding the "optional field" to the other queries or copying the loading method so 1 version uses the optional field and the other doesn't?

I'm in the 2.0 framework also.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

情定在深秋 2024-08-05 20:59:20

我最终使用 reader.GetName(int) 方法找到了解决方案。 我创建了以下方法来包含逻辑。

public bool ColumnExists(IDataReader reader, string columnName)
{
    for (int i = 0; i < reader.FieldCount; i++)
    {
         if (reader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
        {
            return true;
        }
    }

    return false;
}

I ended up finding a solution using the reader.GetName(int) method. I created the below method to encompass the logic.

public bool ColumnExists(IDataReader reader, string columnName)
{
    for (int i = 0; i < reader.FieldCount; i++)
    {
         if (reader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
        {
            return true;
        }
    }

    return false;
}
坚持沉默 2024-08-05 20:59:20

下面将为您提供给定数据读取器的列名称字符串列表。
(请记住,结果是基于上次阅读的结果,因此根据读者阅读的内容,结果可能会有所不同)。

var cols = reader.GetSchemaTable()
                 .Rows
                 .OfType<DataRow>()
                 .Select(row => row["ColumnName"]);

或者检查列是否存在:

public bool ColumnExists(IDataReader reader, string columnName)
{

  return reader.GetSchemaTable()
               .Rows
               .OfType<DataRow>()
               .Any(row => row["ColumnName"].ToString() == columnName);
}

The following will give you a list of the column name strings given a data reader.
(Remember the results are based on the last read so it may not be the same depending on what the reader read).

var cols = reader.GetSchemaTable()
                 .Rows
                 .OfType<DataRow>()
                 .Select(row => row["ColumnName"]);

Or to check if a column exists:

public bool ColumnExists(IDataReader reader, string columnName)
{

  return reader.GetSchemaTable()
               .Rows
               .OfType<DataRow>()
               .Any(row => row["ColumnName"].ToString() == columnName);
}
失去的东西太少 2024-08-05 20:59:20
Enumerable.Range(0, reader.FieldCount).Any(i => reader.GetName(i) == "ColumnName")
Enumerable.Range(0, reader.FieldCount).Any(i => reader.GetName(i) == "ColumnName")
各自安好 2024-08-05 20:59:20

这应该可行,试试这个:

private static bool ColumnExists(SqlDataReader reader, string columnName)
        {
            using (var schemaTable = reader.GetSchemaTable())
            {
                if (schemaTable != null)
                    schemaTable.DefaultView.RowFilter = String.Format("ColumnName= '{0}'", columnName);

                return schemaTable != null && (schemaTable.DefaultView.Count > 0);
            }
        }

This should work, try this:

private static bool ColumnExists(SqlDataReader reader, string columnName)
        {
            using (var schemaTable = reader.GetSchemaTable())
            {
                if (schemaTable != null)
                    schemaTable.DefaultView.RowFilter = String.Format("ColumnName= '{0}'", columnName);

                return schemaTable != null && (schemaTable.DefaultView.Count > 0);
            }
        }
渡你暖光 2024-08-05 20:59:20

看来我的立场是正确的。 我知道你的实际列名在那里,但我走错了路。 此参考帮助澄清了一些事情,但我'我仍然不确定是否有一种优雅的方法来做到这一点。 根据上面的链接改编,您可以获得所有列的列表,其中包含以下内容:

List<string> myCols = new List<string>();
DataTable schema = reader.GetSchemaTable();
foreach (DataRow row in schema.Rows)
{
    myCols.Add(row[schema.Columns["ColumnName"]]);
}

不幸的是,您似乎只能按索引访问 schema.Rows,因此我不确定您是否可以在检查之前先循环遍历行按名字。 在这种情况下,您原来的解决方案似乎更加优雅!

注意:我原来的答案建议简单地通过以下方式检查列是否存在: reader.GetSchemaTable().Columns["optionalfield"]。

Appears I stand corrected. I know your actual column names are in there, but I was going down the wrong path. This reference helped clear things up a bit, but I'm still not sure if there's an elegant way of doing it. Adapted from the above link, you could get a list of all of your columns with the following:

List<string> myCols = new List<string>();
DataTable schema = reader.GetSchemaTable();
foreach (DataRow row in schema.Rows)
{
    myCols.Add(row[schema.Columns["ColumnName"]]);
}

Unfortunately it appears you can only access schema.Rows by index, so I'm not sure you can get around looping through the rows first before checking by name. In that case, your original solution seems far more elegant!

Note: my original answer suggested checking for presence of a column simply by: reader.GetSchemaTable().Columns["optionalfield"].

川水往事 2024-08-05 20:59:20

将其加载到数据表中,然后您可以检查列:

DataTable dataTable = new DataTable();
dataTable.Load(reader);
foreach (var item in dataTable.Rows) 
{
    bool columnExists = item.Table.Columns.Contains("ColumnName");
}

Load it into a DataTable and then you can check for column:

DataTable dataTable = new DataTable();
dataTable.Load(reader);
foreach (var item in dataTable.Rows) 
{
    bool columnExists = item.Table.Columns.Contains("ColumnName");
}
漆黑的白昼 2024-08-05 20:59:20

不需要那么复杂,只需这样:

bool bFieldExists = datareader.GetSchemaTable().Columns.Contains(strFieldName);

Don't need so much complication, just this:

bool bFieldExists = datareader.GetSchemaTable().Columns.Contains(strFieldName);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文