Python MySQL Delete From
- Previous Page MySQL Order By
- Next Page MySQL Drop Table
Delete records
You can use the "DELETE FROM" statement to delete records from an existing table:
Example
Delete any records with the address "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")
Important:Please note the statement mydb.commit()
Changes need to be made, otherwise the table will not be altered at all.
Please note the WHERE clause in the DELETE syntax: The WHERE clause specifies which records should be deleted. If the WHERE clause is omitted, all records will be deleted!
Prevent SQL injection
It is also a good habit to escape any queried value in delete statements.
This is 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")
- Previous Page MySQL Order By
- Next Page MySQL Drop Table