gpt4 book ai didi

python - SQLAlchemy:具有多个 where 条件的 SQL 表达式

转载 作者:太空狗 更新时间:2023-10-29 18:25:53 26 4
gpt4 key购买 nike

我在编写应该是 SQLAlchemy Core 中的简单 SQL 更新语句时遇到了困难。但是,我找不到任何说明如何组合多个 where 条件的文档、示例或教程。我确定它在那里 - 只是找不到它。

这是表格:

self.struct    = Table('struct',
metadata,
Column('schema_name', String(40), nullable=False,
primary_key=True),
Column('struct_name', String(40), nullable=False,
primary_key=True),
Column('field_type', String(10), nullable=True),
Column('field_len', Integer, nullable=True) )

这是插入和更新语句:

def struct_put(self, **kv):
try:
i = self.struct.insert()
result = i.execute(**kv)
except exc.IntegrityError: # row already exists - update it:
u = self.struct.update().\
where((self.struct.c.struct_name==kv['struct_name']
and self.struct.c.schema_name==kv['schema_name'])).\
values(field_len=kv['field_len'],
field_type=kv['field_type'])
result = u.execute()

代码可以很好地处理插入,但会更新表中的所有行。你能帮我理解这个 where 子句的语法吗?欢迎所有建议 - 提前致谢。

编辑:更正后的条款如下所示:

        where((and_(self.struct.c.parent_struct_name==kv['parent_struct_name'],
self.struct.c.struct_name==kv['struct_name'],
self.struct.c.schema_name==kv['schema_name']))).\

这是一个非常简单的语法,但是考虑到 SQLAlchemy 的许多层,要确定在此上下文中究竟应用了什么是非常困难的。

最佳答案

在我看来,您正在使用 Python 的“and”操作,它的计算结果只会是它周围的一个子句。您应该尝试改用 SQLAlchemy 中的“and_”函数。将这两个子句放在“and_”函数中。

关于python - SQLAlchemy:具有多个 where 条件的 SQL 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9091668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com