MySQL UPDATE and DELETE in Python: Complete Guide
The UPDATE and DELETE operations are crucial CRUD actions for maintaining data. This guide shows you how to perform both safely from Python using mysql.connector.
Complete Python Course:-
SQL Tutorial:-
UPDATE Operation
The UPDATE statement modifies existing rows. Always use a WHERE clause ÔÇö without it, ALL rows update.
UPDATE Employee SET name = 'alex' WHERE id = 110;
Python UPDATE Example
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
passwd="your_password",
database="PythonDB"
)
cur = conn.cursor()
try:
cur.execute("UPDATE Employee SET name = %s WHERE id = %s", ("alex", 110))
conn.commit()
print(f"{cur.rowcount} record(s) updated")
except Exception as e:
conn.rollback()
print("Error:", e)
finally:
conn.close()
DELETE Operation
DELETE FROM Employee WHERE id = 110;
Python DELETE Example
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
passwd="your_password",
database="PythonDB"
)
cur = conn.cursor()
try:
cur.execute("DELETE FROM Employee WHERE id = %s", (110,))
conn.commit()
print(f"{cur.rowcount} record(s) deleted")
except Exception as e:
conn.rollback()
print("Error:", e)
finally:
conn.close()
Best Practices
- Always use WHERE: Prevents accidental mass changes.
- Use Parameterized Queries:
%splaceholders prevent SQL injection. - Backup Before Bulk Operations: Especially in production.
- Commit or Rollback: Wrap in try/except for atomicity.
- Test in Dev First: Run UPDATE/DELETE in a staging environment.
- Use Transactions: For multi-statement consistency.
Preview Before Deleting
# Always run SELECT first
cur.execute("SELECT * FROM Employee WHERE id = %s", (110,))
print(cur.fetchall()) # Confirm which rows are affected
Download New Real Time Projects:- Click here
Conclusion
UPDATE and DELETE are powerful but dangerous. Use parameterized queries, commit on success, rollback on failure, and always include a WHERE clause. For more guides, stay tuned to .
database operations sql
database operations in mysql
database operations in python
python mysql update
python mysql delete
crud python mysql
parameterized queries python
database operations crud