我有两个列名称列表:setcols
和 wherecols
。我想使用 SQLAlchemy 方法构建一个查询,类似于
UPDATE tablename SET setcols[0]= ?, ... WHERE wherecols[0]= ?, ...
我尝试的是
t = sa.table('tablename', *[sa.column(name) for name in setcols+wherecols])
query = t.update(). \
where(t.c[cn] == sa.bindparam(cn) for cn in wherecols).\
values({cn: sa.bindparam(cn) for cn in setcols})
还有这个
query = t.update({cn: sa.bindparam(cn) for cn in setcols}). \
where(t.c[cn] == sa.bindparam(cn) for cn in wherecols)
但是这些都不起作用,我收到以下错误:
sqlalchemy.exc.ArgumentError: SQL expression object or string expected, got object of type <class 'generator'> instead
我已阅读手册并认为要设置的值可以作为字典提供,但我发现我错了......
有人可以帮忙吗?
我正在使用 sqlalchemy-1.1.13。
最佳答案
问题出在你调用where()
的方式上。它需要一个 whereclause
,而不是一个生成器对象。使用例如 and_
或 or_
组合这些生成的谓词:
query = t.update(). \
where(and_(*[t.c[cn] == sa.bindparam(cn) for cn in wherecols])).\
values({cn: sa.bindparam(cn) for cn in setcols})
关于python - 使用 SQLAlchemy 构造 UPDATE .. SET .. WHERE .. 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48096902/