使用 fast_executemany 写入 MS-Access DB 不起作用



我在将数据加载到访问数据库中时遇到问题。出于测试目的,我构建了一个小的转换函数,该函数从hdf文件中获取所有数据集并将其写入accdb。如果没有@event.listens_for(engine, "before_cursor_execute")功能,它可以工作,但速度很慢。有了它,它会产生一种奇怪的行为。它在数据库中只创建一个空表(从第一个 df 开始(并完成执行。for 循环永远不会完成,也不会引发错误。

也许是因为sqlalchemy-access包不支持fast_executemany但找不到有关它的任何相关信息。你们中是否有人对我有一些意见,我可以如何解决它或能够以更快的方式将数据写入数据库?

非常感谢!

import urllib
from pathlib import Path
from sqlalchemy import create_engine, event
# PATHS
HOME = Path(__file__).parent
DATA_DIR = HOME / 'output'
FILE_ACCESS = DATA_DIR / 'db.accdb'
FILE_HDF5 = DATA_DIR / 'Data.hdf'
# FUNCTIONS
def convert_from_hdf_to_accb():
# https://github.com/gordthompson/sqlalchemy-access/wiki/Getting-Connected
driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
conn_str = 'DRIVER={};DBQ={};'.format(driver, FILE_ACCESS)
conn_url = "access+pyodbc:///?odbc_connect={}".format(urllib.parse.quote_plus(conn_str))
# https://medium.com/analytics-vidhya/speed-up-bulk-inserts-to-sql-db-using-pandas-and-python-61707ae41990
# https://github.com/pandas-dev/pandas/issues/15276
# https://stackoverflow.com/questions/48006551/speeding-up-pandas-dataframe-to-sql-with-fast-executemany-of-pyodbc
engine = create_engine(conn_url)
@event.listens_for(engine, "before_cursor_execute")
def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):
if executemany:
cursor.fast_executemany = True
with pd.HDFStore(path=FILE_HDF5, mode="r") as store:
for key in store.keys():
df = store.get(key)
df.to_sql(name=key, con=engine, index=False, if_exists='replace')
print(' IT NEVER REACHES AND DOESNT RAISE AN ERROR :( ')
# EXECUTE
if __name__ == "__main__":
convert_from_hdf_to_accb()

也许是因为sqlalchemy-access包不支持fast_executemany

pyodbc 的fast_executemany功能要求驱动程序支持称为"参数数组"的内部 ODBC 机制,而 Microsoft Access ODBC 驱动程序不支持它们。

参见

https://github.com/mkleehammer/pyodbc/wiki/Driver-support-for-fast_executemany

最新更新