Deleting Data using Connector/Python

Last updated on July 27, 2020

In the last lesson, we saw how to update rows in the tables. In this lesson, we will see examples of how to delete data.

Deleting single row #

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import mysql.connector db = mysql.connector.connect(option_files='my.conf', use_pure=True) cursor = db.cursor(buffered=True) sql1 = "delete from category where name=%s limit 1" data1 = ('php',) cursor.execute(sql1, data1) db.commit() # commit the changes print("Rows affected:", cursor.rowcount) cursor.close() db.close() 

Expected Output:

Rows affected: 1


Deleting rows in bulk #

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import mysql.connector db = mysql.connector.connect(option_files='my.conf', use_pure=True) cursor = db.cursor(prepared=True) sql1 = "delete from post where id=%s" data1 = [ (3,), (4,), (5,), (6,) ] cursor.executemany(sql1, data1) db.commit() # commit the changes print("Rows affected:", cursor.rowcount) cursor.close() db.close() 

Expected Output:

Rows affected: 4