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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:41:09  来源:igfitidea点击:

How to get number of affected rows in sqlalchemy?

pythonsqlalchemy

提问by honzas

I have one question concerning Python and the sqlalchemy module. What is the equivalent for cursor.rowcountin the sqlalchemy Python?

我有一个关于 Python 和 sqlalchemy 模块的问题。cursor.rowcountsqlalchemy Python 中的等价物是什么?

采纳答案by DNS

ResultProxyobjects have a rowcountproperty as well.

ResultProxy对象也有rowcount属性。

回答by Shiplu Mokaddim

rowcountis 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, rowcountis configured by default to return the match count in all cases

此属性返回匹配的行数,这不一定与实际修改的行数相同- 例如,如果给定的 SET 值与那些已经在行中的人。这样的行将被匹配但不会被修改。在具有两种样式的后端(例如 MySQL)上,rowcount默认配置为在所有情况下返回匹配计数

So for both of the following scenarios rowcountwill report 1. Because of Rows matched: 1

所以对于以下两种情况rowcount都会报告1。因为Rows matched: 1

  1. one row changed with updatestatement.

    Query OK, 1 row affected (0.00 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    
  2. same updatestatement is executed.

    Query OK, 0 row affected (0.00 sec)
    Rows matched: 1  Changed: 0  Warnings: 0
    
  1. 一行更改了update语句。

    Query OK, 1 row affected (0.00 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    
  2. 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...]

rowcountwill then return the number of affected rows, because it equals the number of matched rows.

rowcount然后将返回受影响的行数,因为它等于匹配的行数。