首页 > 解决方案 > 旧访问文件和 PYODBC

问题描述

我有很多旧的 Access 文件 (*.mdb) 是在 2010 之前的某些版本的 Access 中创建的。我无法使用 Access 2019 或 OBDC 数据源 x64 中的 64 位驱动程序打开它们,这些驱动程序在 PYODBC 问题和堆栈溢出的答案。

{Microsoft Access Driver (*.mdb, *.accdb)}问题是,“当您尝试使用标准驱动程序使用 PYODBC 打开 Access 文件时收到以下错误,您会怎么做?”

错误信息:

[ODBC Microsoft Access 驱动程序] 无法打开使用以前版本的应用程序创建的数据库。(-1019)")

如果您尝试使用 Access 2019 打开旧的 Access 数据文件,您将收到非常相似的消息。

标签: python-3.xpandasms-accesspyodbc32-bit

解决方案


介绍

有几个步骤可以解决这个问题。

  1. 检查您是否安装了 Access 的 32 位驱动程序 如果没有,请使用 Microsoft Access Database Engine 2010 Redistributable ( https://www.microsoft.com/en-us/download/details.aspx?id=从 Microsoft 安装它们13255 )
  2. 使用 32 位 Python 设置虚拟环境
  3. 选择合适的驱动程序

1.检查32位驱动

在 Windows 搜索栏中搜索 ODBC 并打开 32 位版本。如果你有,Driver do Microsoft Access (*.mdb)那么你完成了这一步。 ODBC 32 位驱动程序

如果您没有看到此驱动程序,则需要使用上面的链接从 Microsoft 下载驱动程序。

2. 设置 32 位 Python 假设您已经安装了 Anaconda。您需要使用执行工作所需的库创建一个 32 位 Python 虚拟环境。这是我在旧访问文件中使用 PYODBC 和 Pandas 所做的。参考:https ://titanwolf.org/Network/Articles/Article?AID=25933ee7-9343-4045-ab83-74ebae601b92

$ set CONDA_SUBDIR=win-32

$ conda create -n py36_32bit python=3.6.5 pandas PYODBC openpyxl spyder

$ conda activate py36_32bit

$ python

Python 3.6.8 |Anaconda, Inc.| 

(default, Feb 21 2019, 18:28:22) [MSC v.1916 32 bit (Intel)] on win32

3. 选择正确的驱动程序 在新的 32 位环境中打开 Spyder 并开始编码。这是一个如何连接旧数据库文件的示例。

    path_to_access = r"full\path\to\file.mdb"
    ###Create the connection string with the 32 bit driver
    connStr = (r"Driver={Driver do Microsoft Access (*.mdb)};"
    r"DBQ="+path_to_access+";")
    ### Connect to the database
    cnxn = pyodbc.connect(connStr)
    cursor = cnxn.cursor()
    ### Print out the table names in the database.
    for table_info in cursor.tables(tableType='TABLE'):
         print(f'Table: {table_info.table_name}')
    ### Close the connection to the file. 
    cursor.close()
    cnxn.close()

有关其他参考资料,我强烈推荐此页面与旧访问文件交互。Pandas 还有一个很好的工具,可以使用pandas.read_sql().

旧访问文件参考: https ://www.barenakedcoder.com/blog/2020/04/python-and-microsoft-access-files/


推荐阅读