将访问数据库文件中的所有数据显示在 datagridview 中,而无需知道表名

本文关键字:datagridview 显示 文件 数据库 访问 数据 | 更新日期: 2023-09-27 18:32:46

实际上我正在尝试连接我的wform数据挖掘应用程序以在应用程序运行时通过打开对话框访问数据库文件。由于我正在尝试连接到任何未知的数据库文件(mdb/accdb),因此,我对它的表名一无所知。但是要将数据库连接到datagridview,您必须提供sql查询作为命令。我的问题是,有没有办法可以在任何连接的访问数据库文件中加载所有数据(记录),而无需指定/知道访问数据库文件的表名称。

谢谢

将访问数据库文件中的所有数据显示在 datagridview 中,而无需知道表名

您可以先获取或列出表名。正如海登先生在他的博客 http://davidhayden.com/blog/dave/archive/2006/10/01/GetListOfTablesInMicrosoftAccessUsingGetSchema.aspx 中所解释的那样

// 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<string> tableNames = new List<string>();
for (int i=0; i < userTables.Rows.Count; i++)
tableNames.Add(userTables.Rows[i][2].ToString());

检索 MS 访问文件中的表列表