如何使用 C# 连接到 MS Access 文件 (mdb)?

如何使用 C# 连接到 MS Access 文件 (mdb)?

问题描述:

我正在尝试连接到一个 mdb 文件,我知道我需要 Microsoft.OLEDB.JET.4.0 数据提供程序.不幸的是,我没有在(大学)机器上安装它.因为,他们不提供该提供者,所以我相信应该有办法解决.

I'm trying to connect to a mdb file and I understand that I would need Microsoft.OLEDB.JET.4.0 data provider. Unfortunately, I do not have it installed on the (University) machine. Since, they don't provide that provider, I believe there should be a way around.

如何在没有 Microsoft.OLEDB.JET.4.0 的情况下连接到文件,或者有其他替代方法吗?

How can I connect to the file without Microsoft.OLEDB.JET.4.0 or is there any alternative ?

我有以下提供商:

我曾尝试使用 OLE DB Provider for Microsoft Directory Services,在测试连接时,我得到测试成功,但提供程序不接受某些设置".我拿了那个字符串并使用它,但我得到 ADsDSOObject' failed with no error message, result code: DB_E_ERRORSINCOMMAND(0x80040E14).

I have tried using OLE DB Provider for Microsoft Directory Services, to which while testing connection, I get 'Test succeeded but some settings were not accepted by the provider'. I took that string and used it anyway and I got ADsDSOObject' failed with no error message available, result code: DB_E_ERRORSINCOMMAND(0x80040E14).

最简单的连接方式是通过 OdbcConnection 使用这样的代码

The simplest way to connect is through an OdbcConnection using code like this

using System.Data.Odbc;

using(OdbcConnection myConnection = new OdbcConnection())
{
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    //execute queries, etc

}

其中 myConnectionString 是这样的

where myConnectionString is something like this

myConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};" + 
"Dbq=C:mydatabase.mdb;Uid=Admin;Pwd=;

参见 ConnectionStrings

或者,您可以创建一个 DSN,然后在您的连接字符串中使用该 DSN

In alternative you could create a DSN and then use that DSN in your connection string

  • 打开控制面板 - 管理工具 - ODBC 数据源经理
  • 转到系统 DSN 页面并添加新的 DSN
  • 选择 Microsoft Access 驱动程序 (*.mdb) 并按 END
  • 设置 DSN 的名称(在本例中选择 MyDSN)
  • 选择要使用的数据库
  • 尝试使用 Compact 或 Recover 命令查看连接是否正常

现在你的 connectionString 可以这样写了

now your connectionString could be written in this way

myConnectionString = "DSN=myDSN;"