Python: Number of rows affected by cursor.execute("SELECT …)

前端 未结 6 1388
迷失自我
迷失自我 2020-12-13 08:36

How can I access the number of rows affected by:

cursor.execute(\"SELECT COUNT(*) from result where server_state=\'2\' AND name LIKE \'\"+digest+\"_\"+charse         


        
6条回答
  •  旧时难觅i
    2020-12-13 08:50

    From PEP 249, which is usually implemented by Python database APIs:

    Cursor Objects should respond to the following methods and attributes:

    […]

    .rowcount
    This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like 'select') or affected (for DML statements like 'update' or 'insert').

    But be careful—it goes on to say:

    The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface. [7]

    Note:
    Future versions of the DB API specification could redefine the latter case to have the object return None instead of -1.

    So if you've executed your statement, and it works, and you're certain your code will always be run against the same version of the same DBMS, this is a reasonable solution.

提交回复
热议问题