Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 863
island Avatar asked Aug 26 '16 10:08

island


2 Answers

You can do this by cursor.rowcount after executing stage. Ff return value of this is opposite of 0 it means one or more rows are affected.

like image 129
Reza Tanzifi Avatar answered Sep 25 '22 11:09

Reza Tanzifi


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)
like image 26
Elzo Valugi Avatar answered Sep 23 '22 11:09

Elzo Valugi