Python MySQL Delete From

Record verwijderen

Je kunt records verwijderen van bestaande tabellen met de DELETE FROM-statement:

Example

Verwijder alle records met de adres "Mountain 21":

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Mountain 21'
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")

Run Instance

Belangrijk:Let op met de zin mydb.commit()Moet worden aangepast, anders zal de tabel geen verandering ondergaan.

Let op met de WHERE-clausule in de DELETE-syntaxis: De WHERE-clausule specificeert welke records moeten worden verwijderd. Als de WHERE-clausule wordt overgeslagen, worden alle records verwijderd!

Prevent SQL injection

It is also a good habit to escape any queried value in delete statements.

This is done to prevent SQL injection, a common network hacker technique that can damage or abuse your database.

The mysql.connector module uses placeholders %s To escape values in delete statements:

Example

Using placeholders %s Methods to escape values:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address =" %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")

Run Instance