VB.NET擷取Access資料庫表結構

來源:互聯網
上載者:User

.net中常會遇到讀取Access資料庫中表結構,可以考慮方便的GetOleDbSchemaTable

架構表以 DataTable 的形式返回,該資料表與由 schema 參數指定的 OLE DB 結構描述資料列集具有相同的格式。使用 restrictions 參數篩選要返回到 DataTable 中的行(例如,通過指定對錶名、類型、所有者或架構的限制)。在將值傳遞給數組時,對於不包含值的數組元素,請將Null 字元串或 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.