Python MySQL Delete Explained with Example

In python, you can use cursor.execute() to execute a DELETE sql statement to delete a table or rows.

Syntax

cursor.execute(“DELETE FROM table_name WHERE condition”)

Delete a User

import mysql.connector

# Establish connection to MySQL server
connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="password",
    database="mydatabase"
)

cursor = connection.cursor()

# Delete records from the 'users' table based on a condition
delete_query = "DELETE FROM users WHERE id = 1"
cursor.execute(delete_query)

# Commit the changes
connection.commit()

# Verify the deletion
cursor.execute("SELECT * FROM users")
remaining_users = cursor.fetchall()
print("Remaining Users:")
for user in remaining_users:
    print(user)

connection.close()

In this example, you will delete a user where id = 1.

Important: You should use connection.commit() to save the changes permanently.