How to get number of affected rows in sqlalchemy?

前端 未结 3 1780
醉梦人生
醉梦人生 2020-12-02 23:08

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

相关标签:
3条回答
  • 2020-12-02 23:28

    rowcount is not the number of affected rows. Its the number of matched rows. See what doc says

    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

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

    1. one row changed with update statement.

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

      Query OK, 0 row affected (0.00 sec)
      Rows matched: 1  Changed: 0  Warnings: 0
      
    0 讨论(0)
  • 2020-12-02 23:36

    ResultProxy objects have a rowcount property as well.

    0 讨论(0)
  • 2020-12-02 23:40

    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.:

    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.

    0 讨论(0)
提交回复
热议问题