首页 > 解决方案 > 使用多个条件使用 SQLAlchemy/SQLite 更新连接

问题描述

我已经使用以下代码在 SQLite 数据库上成功设置了 ORM 以反映数据库:

Base = automap_base()
conn_string = 'sqlite:///' + wd.replace('\\','\\\\') + sqlite_filename
engine = create_engine(conn_string, echo=True)
@event.listens_for(Table, "column_reflect")
def reflect_col(inspector, table, column_info):
    column_info['key'] = column_info['name'].replace(' ', '_')
Base.prepare(engine, reflect=True)
PpoAward = Base.classes.ppo_award
Accident = Base.classes.accident
session = Session(engine)

我成功地执行了这样的基本查询:

# delete existing accident records for this quarter
session.query(Accident).\
    filter(and_(Accident.accounting_year==acct_year,
                Accident.accounting_qtr == acct_qtr)).delete()
    session.commit()

我正在尝试对 ppo_award 表进行更新连接,但是对此相对较新,我完全迷失在 SQLAlchemy 文档中。我认为 stackoverflow 上还没有一个直接的答案。

我希望能够在 Python 中以一种优雅的方式复制这个 SQL:

UPDATE ppo_award
SET p.ppo_award_accident_id = a.accident_id
FROM ppo_award p
    INNER JOIN accident a ON p.field_1=a.field_1 AND p.field_2=a.field_2 AND p.field_3=a.field_3

字段 1、2 和 3 在事故表中具有唯一约束。

任何帮助将不胜感激。

标签: pythonsqlitesqlalchemy

解决方案


推荐阅读