获取特定表的列名

发布于 2024-09-25 04:55:11 字数 59 浏览 0 评论 0原文

我想获取特定表的所有列名。

我正在使用 msaccess 和 C# .net 2008。

I want to fetch all the column names for specific table..

I am using msaccess and C# .net 2008.

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

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

发布评论

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

评论(6

萤火眠眠 2024-10-02 04:55:11

您可以使用 SchemaOnly CommandBehavior 通过 OleDb 获取给定查询的架构信息GetSchemaTable 方法,如下所示:

var conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND.mdb";
using (var con = new OleDbConnection(conStr))
{
    con.Open();
    using (var cmd = new OleDbCommand("select * from Suppliers", con))
    using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
    {
        var table = reader.GetSchemaTable();
        var nameCol = table.Columns["ColumnName"];
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine(row[nameCol]);
        }
    }
}

You can fetch schema information for a given query through OleDb using the SchemaOnly CommandBehavior and the GetSchemaTable method, as follows:

var conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND.mdb";
using (var con = new OleDbConnection(conStr))
{
    con.Open();
    using (var cmd = new OleDbCommand("select * from Suppliers", con))
    using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
    {
        var table = reader.GetSchemaTable();
        var nameCol = table.Columns["ColumnName"];
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine(row[nameCol]);
        }
    }
}
傲性难收 2024-10-02 04:55:11

bubi 方法针对特定表的变体:

public List<string> GetTableColumnNames(string tableName)
{
  var conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND.mdb";
  using (var connection = new OleDbConnection(conStr))
  {
    connection.Open();
    var schemaTable = connection.GetOleDbSchemaTable(
      OleDbSchemaGuid.Columns,
      new Object[] { null, null, tableName });
    if (schemaTable == null)
      return null;

    var columnOrdinalForName = schemaTable.Columns["COLUMN_NAME"].Ordinal;

    return (from DataRow r in schemaTable.Rows select r.ItemArray[columnOrdinalForName].ToString()).ToList();
  }
}

当然,首先您可能需要在获取其列名之前检查该表是否确实存在:

public bool TableExists(string tableName)
{
  var conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND.mdb";      
  using (var connection = new OleDbConnection(conStr))
  {
    connection.Open();
    var tables = connection.GetSchema("Tables");
    var tableExists = false;
    for (var i = 0; i < tables.Rows.Count; i++)
    {
      tableExists = String.Equals(tables.Rows[i][2].ToString(),
                           tableName,
                           StringComparison.CurrentCultureIgnoreCase);
      if (tableExists)
        break;
    }
    return tableExists;
  }
}

A variant of bubi's method for a specific table:

public List<string> GetTableColumnNames(string tableName)
{
  var conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND.mdb";
  using (var connection = new OleDbConnection(conStr))
  {
    connection.Open();
    var schemaTable = connection.GetOleDbSchemaTable(
      OleDbSchemaGuid.Columns,
      new Object[] { null, null, tableName });
    if (schemaTable == null)
      return null;

    var columnOrdinalForName = schemaTable.Columns["COLUMN_NAME"].Ordinal;

    return (from DataRow r in schemaTable.Rows select r.ItemArray[columnOrdinalForName].ToString()).ToList();
  }
}

Of course first you might want to check if the table actually exists before getting its column names:

public bool TableExists(string tableName)
{
  var conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND.mdb";      
  using (var connection = new OleDbConnection(conStr))
  {
    connection.Open();
    var tables = connection.GetSchema("Tables");
    var tableExists = false;
    for (var i = 0; i < tables.Rows.Count; i++)
    {
      tableExists = String.Equals(tables.Rows[i][2].ToString(),
                           tableName,
                           StringComparison.CurrentCultureIgnoreCase);
      if (tableExists)
        break;
    }
    return tableExists;
  }
}
素染倾城色 2024-10-02 04:55:11

这将检索所有表和视图的所有列

        DataTable schemaTable = ((OleDbConnection)jetConnection).GetOleDbSchemaTable(
          System.Data.OleDb.OleDbSchemaGuid.Columns,
          new object[] { null, null, null, null });

This retrieves all the columns of all tables and views

        DataTable schemaTable = ((OleDbConnection)jetConnection).GetOleDbSchemaTable(
          System.Data.OleDb.OleDbSchemaGuid.Columns,
          new object[] { null, null, null, null });
×眷恋的温暖 2024-10-02 04:55:11

我在尝试构建 C# 应用程序来迁移 Access 数据库时发现了这篇文章。我要迁移的数据库是带有 .accdb 扩展名的 Access 2007/2010 文件。

如果您在具有备注或附件列(在 accdb 文件中可用)的表上使用此代码,它将返回这些列的类型为字符串 (wchar)。

我很难找到有关如何处理这些类型的列的大量信息,因此我想提供一个指向帮助我弄清楚如何处理它们的文章的链接:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/d15606f9-f38d -4a1b-8ce3-000c558e79c5

我采用了该线程中的底部示例并将其转换为 C#。我确实必须将此 using 语句添加到模块中,以避免编辑对“AccessDao”的所有引用:

using AccessDao = Microsoft.Office.Interop.Access.Dao;

我对添加旧线程表示歉意,但我使用此线程作为编写代码的起点并且没有立即意识到这个问题。

I found this article while trying to build a C# application to migrate an Access database. The database I'm migrating is an Access 2007/2010 file with .accdb extension.

If you use this code on a table that has Memo or Attachment columns (available in accdb files), it will return the type of these columns as string (wchar).

I had trouble finding much information about how to deal with these types of columns, so I wanted to provide a link to the article that helped me figure out how to handle them:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/d15606f9-f38d-4a1b-8ce3-000c558e79c5

I took the bottom example in that thread and converted it to C#. I did have to add this using statement to the module to avoid having to edit all of the references to "AccessDao":

using AccessDao = Microsoft.Office.Interop.Access.Dao;

My apologies for tacking onto an old thread, but I used this thread as a starting point for writing my code and didn't realize this gotcha right away.

无风消散 2024-10-02 04:55:11

以下代码用于按照列名称在 Access 表中出现的顺序获取列名称。此处其他答案中的示例按字母顺序返回列名称(至少对我来说......使用 Microsoft Access Database Engine 2016 Redistributable 和 .NET Core 3.1)。

基于qnaninf的代码示例:

var schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tableName });
var columnOrdinalForName = schemaTable.Columns["COLUMN_NAME"].Ordinal;
var columnOrdinalForOrdinal = schemaTable.Columns["ORDINAL_POSITION"].Ordinal;
var rows = schemaTable.Rows;
var columns = from DataRow r in schemaTable.Rows
                orderby r.ItemArray[columnOrdinalForOrdinal]
                select new
                {
                    Ordinal = r.ItemArray[columnOrdinalForOrdinal].ToString(),
                    ColumnName = r.ItemArray[columnOrdinalForName].ToString()
                };

Here's code to get the column names in the order they appear in the Access table. The examples in the other answers here return the column names in alphabetical order (at least for me... using the Microsoft Access Database Engine 2016 Redistributable and .NET Core 3.1).

Based on qnaninf's code example:

var schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tableName });
var columnOrdinalForName = schemaTable.Columns["COLUMN_NAME"].Ordinal;
var columnOrdinalForOrdinal = schemaTable.Columns["ORDINAL_POSITION"].Ordinal;
var rows = schemaTable.Rows;
var columns = from DataRow r in schemaTable.Rows
                orderby r.ItemArray[columnOrdinalForOrdinal]
                select new
                {
                    Ordinal = r.ItemArray[columnOrdinalForOrdinal].ToString(),
                    ColumnName = r.ItemArray[columnOrdinalForName].ToString()
                };
仙女山的月亮 2024-10-02 04:55:11

您可以从 MS Access 数据库中获取 Vb.net 和 Oledb 中的列名称,如下所示。

  'In Vb.net with OleDb


    Dim adapter As new OleDb.OleDbDataAdapter
    Dim ds As New DataSet
    cmd.CommandText = "select * from table_name where 1=2"

    adapter.SelectCommand = cmd
    adapter.Fill(ds)
    adapter.Dispose()
    cmd.Dispose()


    For Each dr In ds.Tables(0).Columns
        ComboBox1.Items.Add(dr.ToString) 'The Column name will come in this combobox
    Next

You can get the column names in Vb.net and Oledb from MS access database as follows.

  'In Vb.net with OleDb


    Dim adapter As new OleDb.OleDbDataAdapter
    Dim ds As New DataSet
    cmd.CommandText = "select * from table_name where 1=2"

    adapter.SelectCommand = cmd
    adapter.Fill(ds)
    adapter.Dispose()
    cmd.Dispose()


    For Each dr In ds.Tables(0).Columns
        ComboBox1.Items.Add(dr.ToString) 'The Column name will come in this combobox
    Next
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文