【问题标题】:Specifying pyODBC options (fast_executemany = True in particular) using SQLAlchemy使用 SQLAlchemy 指定 pyODBC 选项(特别是 fast_executemany = True)
【发布时间】:2020-03-12 02:49:33
【问题描述】:

我想在使用 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?
  • pyODBC - 4.0.21; SQLAlchemy - 1.1.13

标签: python sqlalchemy pyodbc


【解决方案1】:

为 pyodbc 试试这个

crsr = cnxn.cursor()
crsr.fast_executemany = True

【讨论】:

  • 我应该使用crsr.executemany() 来执行我的语句吗?
  • 谢谢,它成功了!虽然有点苦乐参半。原则上,那时不需要 SQLAlchemy... :)
  • 是的。它适用于 pyofbc,而不适用于 sqlalchemy。
【解决方案2】:

从 1.3 版本开始,SQLAlchemy 已经直接支持fast_executemany,例如,

engine = create_engine(connection_uri, fast_executemany=True)

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多