Python: 如何获取使用 MySQLdb 删除的行数

Python: How to get number of rows deleted with MySQLdb

我有下面的代码,它删除日期列值为 current_date 的 table 中的所有行。

db = MySQLdb.connect("localhost",'root','XXXX','XXXX')
cur = db.cursor()
query = "delete from RealTimeData where date = current_date()"
cur.execute(query)
db.commit()

现在,我怎么知道我的查询从 table 中删除了多少行? 我试过 fetchone() 它正在返回 None

您可以使用 Cursor.rowcount 属性:

cur.execute(query)
deleted_row_count = cur.rowcount

根据文档,

.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 ). [9]

使用 Python 2.7.5,MySQLdb 版本 1.2.5 in Linux:

关键是 API returns .rowcount 仅用于 SELECT、INSERT 和 UPDATE。来自 https://www.python.org/dev/peps/pep-0249/:

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

请注意,没有 提及正在为 DELETE 更新此属性。关闭我的旧游标并在我的应用程序中创建一个新游标,我在 DELETE 语句后看到 .rowcount 的结果为 -1,与 PEP249 中记录的完全一样。 (以后注意:return 可能会更改为 None 而不是 -1。)

所以,B 计划:

with ... as mycursor:
    mycursor.execute("DELETE FROM mytable WHERE id = %s", params=(myindex,))
    mycursor.execute("SELECT ROW_COUNT() as rowcount")
    rows = mycursor.fetchall()
    rowcount = rows[0].get('rowcount', -1)

现在,变量 rowcount 包含执行 DELETE SQL 命令删除的行数。

为什么不使用 multi=True 参数?来自 https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html:

If multi is set to True, execute() is able to execute multiple statements specified in the operation string. It returns an iterator that enables processing the result of each statement. However, using parameters does not work well in this case, and it is usually a good idea to execute each statement on its own.

(强调我的。)使用此代码技术,我能够验证 DELETE 语句确实删除了指定的记录。