First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.

How to Delete MySQL Records in Python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import mysql.connector

mydb = mysql.connector.connect(
  host = "localhost",
  user = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'The Rockies'"
mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) deleted")

Prevent SQL Injection in MySQL queries through Python

Specify the injected variable as the second argument to the execute command as below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import mysql.connector

mydb = mysql.connector.connect(
  host = "localhost",
  user = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()

sql = "DELETE FROM customers WHERE address = %s"
adr = ("The Rockies", )

mycursor.execute(sql, adr)

mydb.commit()

print(mycursor.rowcount, "record(s) deleted")