Skip to main content
 首页 » 编程设计

python (pyodbc):Run ms access query from python results to size error

2024年10月01日7Free-Thinker

我在 python 3.5 上使用 pyodbc 和 pandas,以便将大约 10000 行数据从 MS Access 2010 加载到数据框中,然后计算一些相关性。

当我尝试使用下面的代码来查看生成器的功能时,代码打印了 ~10000 行中的大约 9600 行,然后出现以下错误:

[Microsoft][ODBC Microsoft Access Driver] The query cannot be completed. Either the size of the query is larger than the maximum size of a database (2 GB), or there is not enough temporary storage space on the disk to store the query result.

**Code:** 
 
Import pyodbc 
import pandas as pd 
 
con = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' 
                     r'DBQ=MyDB.mdb;') 
cur - con.cursor() 
sql = "SELECT * from [query table]" # I have a query table which is pivoting the data inside the access. 
 
def gen(cursor, sql): 
   cursor.execute(sql) 
   While True: 
       row = cursor.fetchone() 
       if row is None: 
           break 
       yield row 
 
for x in gen(cur,sql): 
    print(x) 

我已经定义了另一个函数,它获取生成器的行并将它们附加到列表,然后附加到 pd.Dataframe,但生成器似乎没有完成这项工作。

我压缩并修复了数据库,但没有成功。另外,目前 mdb 文件的大小不超过 500mb。

你能告诉我如何克服这个错误吗?

非常感谢。

请您参考如下方法:

建立连接时,pyodbc 根据 Python 的 DB-API 规范默认为 autocommit=False。因此,当执行第一个 SQL 语句时,ODBC 开始一个数据库事务,该事务在 Python 代码执行 .commit() 或 .rollback() 之前一直有效连接。

显然,当您处理结果集中的行时,Access 数据库引擎积累了越来越多关于“事务”的信息,最终导致内存不足错误。将 pyodbc 连接设置为 autocommit=True 告诉 Access 数据库引擎不要费心跟踪任何与事务相关的信息,从而避免错误。