簡體   English   中英

sqlalchemy where 子句中動態使用and_

[英]sqlalchemy dynamic use of and_ in where clause

我正在嘗試使用 sqlalchemy 來構建刪除查詢。 delete 子句的 where 部分應動態構造以滿足多個條件。 例如:

DELETE FROM table
WHERE table.col1 = x1
  AND table.col2 = x2
  AND ...

以下是我擁有的代碼的簡化部分。

def upsert(key_col):
    
...
            
    # Build the WHERE clause of your DELETE statement from rows in the dataframe.
    cond = df.apply(lambda row: sa.and_(detail_table.c[key_col] == row[key_col]), axis=1)
    cond = sa.or_(*cond)
    
    # Define and execute the DELETE
    delete = detail_table.delete().where(cond)
    with engine.connect() as conn:
        conn.execute(delete)

...

這適用於從具有單個主鍵列的表中刪除行。 我希望能夠將key_col作為具有復合主鍵的表的列表傳遞。

我可以做類似的事情

cond = df.apply(lambda row: sa.and_(detail_table.c[key_col[0]] == row[key_col[0]], 
                                    detail_table.c[key_col[1]] == row[key_col[1]],
                                    detail_table.c[key_col[2]] == row[key_col[2]]), 
                                    axis=1)

但我希望能夠根據key_col的大小在運行時動態創建上述內容。 我猜有更好的方法來使用 sqlalchemy 執行這樣的刪除查詢。

SQLAlchemy 將接受多個.where結構並將它們組合在一起,例如,

import sqlalchemy as sa

engine = sa.create_engine("mssql+pyodbc://@mssqlLocal64", echo=True)

detail_table = sa.Table(
    "#detail_table",
    sa.MetaData(),
    sa.Column("col1", sa.Integer),
    sa.Column("col2", sa.Integer),
)
detail_table.create(bind=engine)

# test data
criteria = [(detail_table.c.col1, 3), (detail_table.c.col2, 5)]

del_stmt = detail_table.delete()
for crit in criteria:
    col, val = crit
    del_stmt = del_stmt.where(col == val)

with engine.begin() as conn:
    conn.execute(del_stmt)
"""console output:
sqlalchemy.engine.base.Engine DELETE FROM [#detail_table] WHERE [#detail_table].col1 = ? AND [#detail_table].col2 = ?
sqlalchemy.engine.base.Engine (3, 5)
"""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM