sqlalchemy - 如何获得更新方法结果?

时间:2014-12-25 10:56:33

标签: sqlalchemy

我执行update方法:

# connect db to get `conn`
# get metadate which is table `account`
u = account.update().where(account.c.ID == 9).values(USERNAME='k9')
r = conn.execute(u)

如何才能让update取得成功? 我检查了文档,但没找到......

或许我只是不在乎这个?

rResultProxyupdate操作会自动提交并关闭。

THX:)


APPEND

THX @Lucas Kahlert的回答,好的一点!

rowcount满足我的问题。

doc-rowcount

This attribute returns the number of rows matched, 
which is not necessarily the same as the number of rows that were actually modified

In [7]: u = account.update().\
        where( and_((account.c.ID == 4), (account.c.PWD =='4297f44b1'))).\
        values(PWD='hahahaha')

In [8]: print u
UPDATE `ACCOUNT` SET `PWD`=%s WHERE `ACCOUNT`.`ID` = %s AND `ACCOUNT`.`PWD` = %s

In [11]: rst = conn.execute(u)

In [12]: rst.rowcount  # found row and did update action
Out[12]: 1L

In [13]: rst = conn.execute(u)

In [14]: rst.rowcount  # found row but value is same, so do not do update action
Out[14]: 0L

1 个答案:

答案 0 :(得分:3)

您可以使用rowcount的{​​{1}}属性检查查询影响的行数。 ResultProxy告诉您,rowcount条件匹配了多少行。这与受影响的行不同(请参阅this question),但应根据您的情况执行此操作。

没有行受影响

如果您的条件没有匹配行,则无论WHERE语句中的数据是否正确,都将执行查询。

违反约束

如果行匹配并且您尝试使用无效的数据集更新行,则SQLAlchemy将引发约束违例异常(例如UPDATE)。在这种情况下,您可以捕获异常并将其用于“成功”检查。

如果在sqlalchemy.exc.IntegrityError期间没有发生约束违规,则该语句将默认成功。

UPDATE