【发布时间】:2012-02-23 21:18:35
【问题描述】:
我在编写 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 的许多层,很难确定在此上下文中究竟应用了什么。
【问题讨论】:
-
使用 and_() 的捷径是将多个 where() 子句链接在一起。所以:.where(a==1).where(b==2).where(c==3)。见docs。
-
这可能也有帮助:
from sqlalchemy import and_
标签: python sqlalchemy