SQLAlchemy如何批量调用存储函数

2024-05-19 02:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要连续几百次调用一个存储函数, 在DB的一次往返行程中这样做将是一个巨大的进步, 下面是我想在伪代码中执行的操作:

args_for_multiple_calls = [
  {"a1": 1, "a2": "dfg4"),
  {"a1": 4, "a2": "ger"),
  {"a1": 2, "a2": "sfg3"),
]

connection.executemany("select my_stored_func(:a1, :a2)")

SQLAlchemy支持这一点吗?你知道吗


Tags: 函数代码a2fordba1argsconnection
2条回答

SQLAlchemy提供executemany()作为^{}的一部分:

session.execute("select my_stored_func(:a1, :a2)", args_for_multiple_calls)

executemany()是否真正支持SELECT查询取决于驱动程序。另外请记住,虽然这可能会减少往返开销,但由于查询执行开销的原因,它可能仍然很慢(即,如果存储过程只执行一个INSERT并且运行存储过程1000次,那么它将比一个有1000行的INSERT慢)。你知道吗

SQLAlchemy没有这样的功能。这些“低级”命令如:insert、insertmany、callproc、execute、cursor等由DBAPIPython DB API Specification)驱动程序提供,如cx-Oracle、psycopg2、MySQL-Python等。。。SQLAlchemy只是代理DBAPI驱动程序提供的这些函数。你知道吗

如果需要执行函数,应使用callproc游标方法:

args_for_multiple_calls = [
     {"a1": 1, "a2": "dfg4"),
     {"a1": 4, "a2": "ger"),
     {"a1": 2, "a2": "sfg3"),
]

conn = engine.raw_connection()
try:
    cursor = conn.cursor()
    for x in args_for_multiple_calls:
         cursor.callproc("my_stored_func", [x['a1'], x['a2']])
         results = list(cursor.fetchall())
         conn.commit()
   cursor.close()
finally:
   conn.close()

相关问题 更多 >

    热门问题