【问题标题】:How do I get a list of columns in an Access database using C#?如何使用 C# 获取 Access 数据库中的列列表?
【发布时间】:2014-08-15 16:53:12
【问题描述】:

在运行时,如何在 Access 中获取表中的列列表?我不想要表中的数据,只想要列名和类型。

编辑:我忘了提到我使用的是 C#。

【问题讨论】:

  • Get column names的可能重复
  • tl;博士:Set db = CurrentDb() Set rs1 = db.OpenRecordset("Table1") Dim fld As DAO.Field For Each fld In rs1.Fields 'do stuff Next
  • 还可以查看the field object,了解您可以从中获得什么

标签: c# ms-access


【解决方案1】:

您想要遍历表定义的字段属性。我列出了两种循环属性的方法。

C# 解决方案(使用System.DataSystem.Data.OleDb

https://stackoverflow.com/a/864382/2448686

VBA 解决方案

Public Function GetTableDetails()
    Dim db As Database
    Dim td As TableDef

    Set db = CurrentDb
    Set td = db.TableDefs("tableName")

    Dim i As Long
    For i = 0 To td.Fields.Count - 1
        Debug.Print td.Fields(i).Type
    Next

    Dim f As Field
    For Each f In td.Fields
        Debug.Print f.Type
    Next
End Function

【讨论】:

  • 您从哪个库获取这些对象?
  • 我相信如果没有明确说明,它默认为DAO。
  • 最好明确使用DAO
  • @JonathanAllen 我认为 C# 中的库是 Microsoft.Office.Interop.AccessMicrosoft.Office.Interop.Access.Dao。稍后我将不得不确认。
  • 我宁愿避免使用该命名空间中的任何内容。我真的不能指望他们安装办公室。另一方面,通过 COM interopt 直接 DAO 是合理的。
【解决方案2】:

使用 VBA:

dim db as DAO.Database, rs as DAO.Recordset, f as DAO.Field
set db = currentDb()
set rs = db.openRecordset("yourTable", dbOpenDynaset, dbReadOnly)
with rs
    for each f in rs.Fields
        ' Simple example: print to the inmediate window
        debug.print f.Name
    next f
end with

未经测试: 使用Recordset 对象,而不是TableDef 对象:

dim db as DAO.Database, t as DAO.TableDef, f as DAO.Field
set db = currentDb()
set t = db.TableDefs("yourTable")
with t
    for each f in t.Fields
        debug.print f.name
    next f
end with

【讨论】:

  • 嗯,那不是把整个表发送给客户端吗?
  • @JonathanAllen 已更新以解决您的问题。 AFAIK 当您使用 dbOpenDynaset 时,需要时会检索行(如果您使用 dbOpenSnapshot,则必须将整个记录集加载到 RAM 中)
猜你喜欢
  • 2011-09-03
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多