为什么 OleDbConnection 在 64 位进程上抛出 InvalidOperationException 而在 32 位进程上抛出 OleDbException

Why OleDbConnection throws InvalidOperationException on 64-bit process and OleDbException on 32-bit process

我不太确定为什么 32 位和 64 位 运行 环境中的异常差异。我正在使用 Visual Studio 2019 测试下一个代码,并将平台从 x86 更改为 x64,反之亦然-

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Public\Documents\my.accdb";
System.Data.Common.DbConnection connection = new System.Data.OleDb.OleDbConnection(connectionString);

try
{
  connection.Open();
}
catch (InvalidOperationException e)
{
  // occurs when running on 64-bit runtime
}
catch (OleDbException e)
{
  // occurs when running on 32-bit runtime
}

请注意,我没有安装 Microsoft Access 2013/2016 Runtime。为了成功连接到 accdb 文件,您必须安装它,但我正在测试用户是否没有安装它。

我很好奇为什么 OleDbException 也不会出现在 64 位或 x64 平台上?

编辑

InvalidOperationException 消息:

'Microsoft.Jet.OLEDB.4.0' 提供程序未在本地计算机上注册。

OleDbExceptionMessage:

无法识别的数据库格式 'C:\Users\Public\Documents\my.accdb'。

I'm curious why OleDbException does not occur on 64-bit or x64 platform as well?

它不会出现在 64 位上,因为 64 位没有 'Microsoft.Jet.OLEDB.4.0' 提供程序。

对于 32 位,问题似乎是驱动程序无法读取 accdb 文件。对于 64 位,问题是驱动程序 甚至不存在

根据https://docs.microsoft.com/en-us/office/troubleshoot/access/jet-odbc-driver-available-32-bit-version

INTRODUCTION

The Microsoft OLE DB Provider for Microsoft Jet and the Microsoft Access ODBC driver (Jet ODBC driver) provide an interface to Microsoft Office Access databases. The Microsoft OLE DB Provider for Jet and the Jet ODBC driver are available in 32-bit versions only.

More Information

We do not provide a 64-bit version of the Microsoft OLE DB Provider for Jet. Additionally, we do not provide a 64-bit version of the Jet ODBC driver. If you use the Microsoft OLE DB Provider for Jet or the Jet ODBC driver to connect to a data source in a 64-bit environment, you experience different problems.

For example, you have a 32-bit application that uses the Microsoft OLE DB Provider for Jet. If you migrate the application to run in the 64-bit mode, the application cannot connect to the data source by using the Microsoft OLE DB Provider for Jet. This issue occurs because the application requires a 64-bit version of the Microsoft OLE DB Provider for Jet.

However, we still have the 32-bit version of the Microsoft OLE DB Provider for Jet and the 32-bit version of the Jet ODBC driver. In a 64-bit Windows environment, you can run an application in the 32-bit mode. Therefore, the application can use the 32-bit version of the Microsoft OLE DB Provider for Jet or the 32-bit version of the Jet ODBC driver.

最简单的解决方案可能是强制 x86(32 位)。或者让您的代码捕获这两种类型的异常并相应地处理它们。