How one can Delete MySQL Data in Python


First, you’ll need the mysql.connector. In case you are not sure of the right way to get this setup, check with How one can Set up MySQL Driver in Python.

How one can Delete MySQL Data in Python

import mysql.connector

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

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

mydb.commit()

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

Forestall SQL Injection in MySQL queries via Python

Specify the injected variable because the second argument to the execute command as under.

import mysql.connector

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

mycursor = mydb.cursor()

sql = "DELETE FROM clients WHERE handle = %s"
adr = ("The Rockies", )

mycursor.execute(sql, adr)

mydb.commit()

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

Leave a Reply