How to get rows affected in a UPDATE statement by PyMySQL?

island picture island · Aug 26, 2016 · Viewed 17.1k times · Source

I need to update some rows on the MySQL database by PyMYSQL and I want to know how many rows had been changed.

import pymysql
db = pymysql.connect(xxxx)
cur = db.cursor()
sql = "update TABLE set A = 'abc' where B = 'def'"
cur.execute(sql, params)
db.commit()

Answer

Elzo Valugi picture Elzo Valugi · Aug 26, 2016

Mysql provides a special call that will help you achieve exactly that: mysql-affected-rows. This function is especially useful on updates as it will return only the number of rows that were affected, not the ones where the updated value was similar. Documentation is here.

How to use this in Python? The return of execute command will return you exactly this.

affected_rows = cur.execute(sql, params)