使用的GetSchemaTable()来检索仅列名 [英] Using GetSchemaTable() to retrieve only column names

查看:128
本文介绍了使用的GetSchemaTable()来检索仅列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时有可能使用的GetSchemaTable()只检索列名?

Is it possible to use GetSchemaTable() to retrieve only column names?

我一直在试图检索列名使用此方法(只),是可以的。

I have been trying to retrieve Column names (only) using this method, is it possible.

  DataTable table = myReader.GetSchemaTable();

  foreach (DataRow myField in table.Rows)
  {
      foreach (DataColumn myProperty in table.Columns)
      {
          fileconnectiongrid.Rows.Add(myProperty.ColumnName + " = " 
                            + myField[myProperty].ToString());
      }
  }

这代码检索大量表中的数据不需要的,我只需要包含
列名的列表:

This code retrieves a lot of table data unwanted, I only need a list containing column names!:

推荐答案

您需要使用的 的ExecuteReader(CommandBehavior.SchemaOnly))

You need to use ExecuteReader(CommandBehavior.SchemaOnly)):

DataTable schema = null;
using (var con = new SqlConnection(connection))
{
    using (var schemaCommand = new SqlCommand("SELECT * FROM table", con))
    {
        con.Open();
        using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
        {
            schema = reader.GetSchemaTable();
        }
    }
}

SchemaOnly

查询只返回列信息。当使用SchemaOnly,SQL Server的
.NET Framework数据提供之前的声明
与SET FMTONLY上执行。

The query returns column information only. When using SchemaOnly, the .NET Framework Data Provider for SQL Server precedes the statement being executed with SET FMTONLY ON.

列名是在每一行的第一列中。我不认为这有可能忽略其它列信息,比如 Col​​umnOrdinal,ColumnSize,NumericPrecision 等等,因为你不能使用 reader.GetString 但只有 reader.GetSchemaTable 在这种情况下。

The column name is in the first column of every row. I don't think that it's possible to omit the other column informations like ColumnOrdinal,ColumnSize,NumericPrecision and so on since you cannot use reader.GetString but only reader.GetSchemaTable in this case.

但你的循环是不正确,如果你只想列名:

But your loop is incorrect if you only want the column names:

foreach (DataRow col in schema.Rows)
{
    Console.WriteLine("ColumnName={0}", col.Field<String>("ColumnName"));
}

这篇关于使用的GetSchemaTable()来检索仅列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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