VB.NET获取Access数据库表结构

.net中常会遇到读取Access数据库中表结构,可以考虑方便的GetOleDbSchemaTable

架构表以 DataTable 的形式返回,该数据表与由 schema 参数指定的 OLE DB 架构行集具有相同的格式。使用 restrictions 参数筛选要返回到 DataTable 中的行(例如,通过指定对表名、类型、所有者或架构的限制)。在将值传递给数组时,对于不包含值的数组元素,请将空字符串或 null 包括进去。如果将空数组传递到 restrictions,则所有行(每个表一行)都按照默认顺序返回。数组中的值则对应于源表和 DataTable 中列的顺序。限制数组中的每个元素都会与架构行集中对应列的内容进行比较。例如,限制数组中的第一个元素与行集合中的第一列作比较。如果限制元素不为 null,则只会将架构行集合中与限制值完全匹配的行添加到结果 DataTable 中。

下面是MSDN给的例子,返回数据库中的表的列表。

Public Function GetSchemaTable(ByVal connectionString As String) _

As DataTable

Using connection As New OleDbConnection(connectionString)

connection.Open()

Dim schemaTable As DataTable = _

connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, _

New Object() {Nothing, Nothing, Nothing, "TABLE"})

Return schemaTable

End Using

End Function

如果需要返回某一表的字段结构,稍加修改就可以了,具体可以看下MSDN中OleDbSchemaGuid下条目,下面是测试代码:

Dim conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Backup\我的文档\订单1.mdb;Persist Security Info=False"

Using connection As New OleDbConnection(conn)

connection.Open()

Dim schemaTable As DataTable = _

connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, _

New Object() {Nothing, Nothing, "表1", Nothing})

DataGridView1.DataSource = schemaTable '将返回的表在DataGridView1显示

End Using