2

我在将数据加载到访问数据库时遇到问题。出于测试目的,我构建了一个小转换函数,它从 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()
4

1 回答 1

2

可能是因为 sqlalchemy-access 包不支持 fast_executemany

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

也可以看看

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

于 2020-06-25T12:24:43.910 回答