使用pyODBC的fast_executemany加速pandas.DataFrame.to_sql

9 浏览
0 Comments

使用pyODBC的fast_executemany加速pandas.DataFrame.to_sql

我想将一个大型的pandas.DataFrame发送到一个运行MS SQL的远程服务器。我现在的做法是将一个data_frame对象转换为一个元组列表,然后使用pyODBC的executemany()函数发送。大致如下:

import pyodbc as pdb
list_of_tuples = convert_df(data_frame)
connection = pdb.connect(cnxn_str)
cursor = connection.cursor()
cursor.fast_executemany = True
cursor.executemany(sql_statement, list_of_tuples)
connection.commit()
cursor.close()
connection.close()

然后我开始思考是否可以通过使用data_frame.to_sql()方法来加快速度(或者至少更易读)。我想出了以下解决方案:

import sqlalchemy as sa
engine = sa.create_engine("mssql+pyodbc:///?odbc_connect=%s" % cnxn_str)
data_frame.to_sql(table_name, engine, index=False)

现在代码更易读了,但是上传速度至少慢150倍...

在使用SQLAlchemy时有没有一种方法来反转fast_executemany

我使用的是pandas-0.20.3,pyODBC-4.0.21和sqlalchemy-1.1.13。

0