gpt4 book ai didi

c# - 使用 GetSchemaTable() 仅检索列名

转载 作者:太空狗 更新时间:2023-10-29 17:35:05 24 4
gpt4 key购买 nike

是否可以使用 GetSchemaTable() 仅检索列名?

我一直在尝试使用这种方法(仅)检索列名,是否可能。

  DataTable table = myReader.GetSchemaTable();

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

这段代码检索了很多不需要的表数据,我只需要一个列表包含列名!:

最佳答案

您需要使用 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 :

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.

列名位于每一行的第一列。我不认为可以省略其他列信息,例如 ColumnOrdinal、ColumnSize、NumericPrecision 等,因为您不能使用 reader.GetString 而只能使用 reader .GetSchemaTable 在这种情况下。

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

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

关于c# - 使用 GetSchemaTable() 仅检索列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12160976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com