我有两个具有关系的 postgres 表,但没有级联删除集。所以我需要手动从相关表和主表中删除。 我正在使用 sqlalchemy 核心和 psycopg3 驱动程序。
我有以下代码:
identifiers = ['id100', 'id200']
sql = """
delete from related_table where entity_id in (select f.id from main_table f where identifier in (%(id1)s));
delete from main_table where identifier in (%(id2)s)"""
params = {'id1': identifiers, 'id2': identifiers}
conn = self.db_engine.raw_connection()
cursor = conn.cursor()
cursor.execute(text(sql), params=params)
这会导致以下错误:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/local/lib/python3.11/site-packages/psycopg/cursor.py", line 732, in execute
raise ex.with_traceback(None)
psycopg.errors.SyntaxError: cannot insert multiple commands into a prepared statement
无需循环(从而进行往返)执行多个语句的正确方法是什么?
我确信有更好的方法来解决这个问题,但是您可以将每个查询放在一个列表中并通过 for 循环进行迭代。
即:
identifiers = ['id100', 'id200']
sql = ["delete from related_table where entity_id in (select f.id from main_table f where identifier in (%(id1)s));", "delete from main_table where identifier in (%(id2)s)"]
params = {'id1': identifiers, 'id2': identifiers}
conn = self.db_engine.raw_connection()
cursor = conn.cursor()
for queries in sql:
cursor.execute(text(queries), params=params)