Search code examples
pythonmysql-pythondelete-row

Python: How to get number of rows deleted with MySQLdb


I have this below code which deletes all the rows in a table whose date column value is current_date.

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

Now, How can I know that How many rows did my query delete from table? I tried fetchone() it was returning None


Solution

  • You can use Cursor.rowcount attribute:

    cur.execute(query)
    deleted_row_count = cur.rowcount
    

    According to the documentation,

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