简体   繁体   English

SQLAlchemy Core 将 select 语句转换为 update 语句

[英]SQLAlchemy Core convert select statement to update statement

Now, I am using SQLAlchemy Core (NOT ORM) 1.4, and I've got two statements:现在,我使用的是 SQLAlchemy Core (NOT ORM) 1.4,我有两个语句:

stmt1 = sa.select(groups).where(groups.c.id == group_id)
stmt2 = sa.update(groups).where(groups.c.id == group_id)

I would like to know if there's a way to convert stmt1 to stmt2 dynamically because I want to build a statement like this:我想知道是否有办法将stmt1动态转换为stmt2因为我想构建这样的语句:

# doing something to convert stmt1 to stmt2. is it possible?
stmt2 = stmt2.values(**my_dict)

Thank you for your help.谢谢您的帮助。

I found an answer by myself, so I post here.我自己找到了答案,所以我在这里发布。

At first, I asked if I can convert select where to update where using SQLAlchemy core.起初,我问我是否可以使用 SQLAlchemy 核心转换select whereupdate where

It's possible using Select().get_final_froms , but it returns a tuple because we usually select or join with one or more tables.可以使用Select().get_final_froms ,但它返回一个元组,因为我们通常选择或连接一个或多个表。

My purpose was fetching one record which has to be updated.我的目的是获取一条必须更新的记录。

Thus, I derived the select statement from update statement like this:因此,我从 update 语句中派生了 select 语句,如下所示:

stmt_update = sa.update(groups).where(groups.c.id == group_id)

stmt_select = sa.select(stmt_update.table).where(stmt_update.whereclause)

Now I don't have to pass very similar two statements.现在我不必传递非常相似的两个语句。 Thank you.谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM