python(pyodbc):运行 ms 访问查询 python 结果大小错误

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

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

当我尝试使用下面的代码查看生成器的功能时,代码打印了 ~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 数据库引擎正在积累越来越多关于 "transaction" 的信息,最终导致 out-of-memory 错误。将 pyodbc 连接设置为 autocommit=True 告诉 Access 数据库引擎不要费心跟踪任何 transaction-related 信息,从而避免错误。