检索MS Access文件中的表列表

如果我可以在C#中打开与MS Access文件的连接,如何检索Access DB中存在的不同表的列表(如果可能,还可以检索与表关联的任何元数据)?

我刚从David Hayden那里找到了以下解决方案

// Microsoft Access provider factory DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); DataTable userTables = null; using (DbConnection connection = factory.CreateConnection()) { // c:\test\test.mdb connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\test\\test.mdb"; // We only want user tables, not system tables string[] restrictions = new string[4]; restrictions[3] = "Table"; connection.Open(); // Get list of user tables userTables = connection.GetSchema("Tables", restrictions); } List tableNames = new List(); for (int i=0; i < userTables.Rows.Count; i++) tableNames.Add(userTables.Rows[i][2].ToString()); 

这是一些链接:

  • 通过C#显示Access数据库表
  • 演练:使用ADO.NET编辑Access数据库

这是一个VB.NET片段,用于获取访问表的所有列,我知道它不是您正在寻找的,但在列出所有表时类似的原则:

 Dim oleConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & myDB & ";User Id=admin;Password=;") oleConn.Open() Dim schemaTable As DataTable Dim i As Integer schemaTable = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Column s, _ New Object() {Nothing, Nothing, "tblTheTableToListColumns", Nothing}) For i = 0 To schemaTable.Columns.Count - 1 Debug.Print(schemaTable.Rows(i)!COLUMN_NAME.ToStri ng) Next i oleConn.Close()