python 如何在 sqlalchemy 中获取受影响的行数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/702342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get number of affected rows in sqlalchemy?
提问by honzas
I have one question concerning Python and the sqlalchemy module. What is the equivalent for cursor.rowcount
in the sqlalchemy Python?
我有一个关于 Python 和 sqlalchemy 模块的问题。cursor.rowcount
sqlalchemy Python 中的等价物是什么?
回答by Shiplu Mokaddim
rowcount
is notthe number of affected rows. Its the number of matched rows. See what docsays
rowcount
是不是受影响的行数。它是匹配的行数。看看医生怎么说
This attribute returns the number of rows matched, which is not necessarily the same as the number of rows that were actually modified- an UPDATE statement, for example, may have no net change on a given row if the SET values given are the same as those present in the row already. Such a row would be matched but not modified. On backends that feature both styles, such as MySQL,
rowcount
is configured by default to return the match count in all cases
此属性返回匹配的行数,这不一定与实际修改的行数相同- 例如,如果给定的 SET 值与那些已经在行中的人。这样的行将被匹配但不会被修改。在具有两种样式的后端(例如 MySQL)上,
rowcount
默认配置为在所有情况下返回匹配计数
So for both of the following scenarios rowcount
will report 1
. Because of Rows matched: 1
所以对于以下两种情况rowcount
都会报告1
。因为Rows matched: 1
one row changed with
update
statement.Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0
same
update
statement is executed.Query OK, 0 row affected (0.00 sec) Rows matched: 1 Changed: 0 Warnings: 0
一行更改了
update
语句。Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0
update
执行相同的语句。Query OK, 0 row affected (0.00 sec) Rows matched: 1 Changed: 0 Warnings: 0
回答by flxvctr
What Shiplu says is correct of course, however, to answer the question, in many cases you can easily make the matched columns equal the changed columns by including the condition that the value is different in the WHERE clause, i.e.:
Shiplu 所说的当然是正确的,但是,要回答这个问题,在许多情况下,您可以通过在 WHERE 子句中包含值不同的条件,轻松地使匹配的列等于更改的列,即:
UPDATE table
SET column_to_be_changed = "something different"
WHERE column_to_be_changed != "something different" AND [...your other conditions...]
rowcount
will then return the number of affected rows, because it equals the number of matched rows.
rowcount
然后将返回受影响的行数,因为它等于匹配的行数。