我想在使用sqlalchemy将行插入表中的pyodbc驱动程序的fast_executemany选项。默认情况下,代码的运行速度真的很慢。
编辑:
我正在使用PyodBC 4.0.21和SQLalchemy 1.1.13,以及我正在使用的代码的简化示例。
import sqlalchemy as sa
def InsertIntoDB(self, tablename, colnames, data, create = False):
"""
Inserts data into given db table
Args:
tablename - name of db table with dbname
colnames - column names to insert to
data - a list of tuples, a tuple per row
"""
# reflect table into a sqlalchemy object
meta = sa.MetaData(bind=self.engine)
reflected_table = sa.Table(tablename, meta, autoload=True)
# prepare an input object for sa.connection.execute
execute_inp = []
for i in data:
execute_inp.append(dict(zip(colnames, i)))
# Insert values
self.connection.execute(reflected_table.insert(),execute_inp)
尝试pyodbc
crsr = cnxn.cursor()
crsr.fast_executemany = True
从版本1.3开始,sqlalchemy直接支持fast_executemany,例如,
engine = create_engine(connection_uri, fast_executemany=True)