使用sqlalchemy核心更新连接表

时间:2016-03-09 21:35:47

标签: python sqlite join sqlalchemy sql-update

我想根据另一个表中的值更新表中的值。

我有两张桌子:

_LOCATIONR:_id,_status,_uuid

LOCATIONR:_id,_version和一些userdata

如果_version = 0,_uuid =“42”和_id = 1

_status应设置为1

我使用python与sqlalchemy,数据库是sqlite

sc#table LOCATIONR
sc2#table _LOCATIONR
version = 0
uuid = "42"
id = 1
statement = sc2.update().
                where(and_(
                    sc2.c._id == id,
                    sc2.c._id == sc.c._id,
                    sc.c._version == version,
                    sc2.c._uuid == uuid))
r = statement.execute({"_status": 1, "_id": id, "_uuid": uuid})

日志:

2016-03-09 22:08:45,059 INFO sqlalchemy.engine.base.Engine UPDATE "_LOCATIONR" SET _uuid=?, _status=?, _id=? FROM "LOCATIONR" WHERE "_LOCATIONR"._id = ? AND "_LOCATIONR"._id = "LOCATIONR"._id AND "LOCATIONR"._version = ? AND "_LOCATIONR"._uuid = ?
2016-03-09 22:08:45,059 INFO sqlalchemy.engine.base.Engine ('42', 1, 1, 1, 0, '42')
2016-03-09 22:08:45,060 INFO sqlalchemy.engine.base.Engine ROLLBACK

每次执行上面的代码时,sqlalchemy都会进行回滚。 仅当whereclause引用sc时才会发生错误 但由于这些链接,它应该没问题 https://groups.google.com/forum/#!topic/sqlalchemy/HH7Rw65kypA

Update a Joined Table with SQLAlchemy Core

1 个答案:

答案 0 :(得分:1)

statement = sc2.update().where(and_(sc2.c._id == id, sc2.c._uuid == uuid, exists().where(and_(sc2.c._id == sc.c._id, sc.c._version == version))))

作品