Python MySQL – Update and Delete Data

To change or remove existing rows we use the SQL UPDATE and DELETE commands. Like INSERT, they need conn.commit() to save the change. We continue with the users table from the previous chapters.


Update data

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="student"
)
cursor = conn.cursor()

sql = "UPDATE users SET mobile = %s WHERE id = %s"
values = ("9999999999", 1)

cursor.execute(sql, values)
conn.commit()

print(cursor.rowcount, "record updated")

cursor.close()
conn.close()
Output of the above program is

1 record updated

Note: Always use a WHERE condition. Without it the UPDATE changes every row of the table.

You can check the new value with a SELECT.

cursor.execute("SELECT name, mobile FROM users WHERE id = %s", (1,))
print(cursor.fetchone())
Output of the above program is

('Robin', '9999999999')


Delete data

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="student"
)
cursor = conn.cursor()

sql = "DELETE FROM users WHERE id = %s"

cursor.execute(sql, (3,))
conn.commit()

print(cursor.rowcount, "record deleted")

cursor.close()
conn.close()
Output of the above program is

1 record deleted

Note: A DELETE without WHERE removes all the rows of the table. There is no undo, so test with a SELECT first.

Check the remaining rows

cursor.execute("SELECT id, name FROM users")
print(cursor.fetchall())
Output of the above program is

[(1, 'Robin'), (2, 'Maria')]


Summary

  • Use UPDATE ... SET ... WHERE to change rows and DELETE FROM ... WHERE to remove rows.
  • Pass values with %s placeholders.
  • Call conn.commit() after every change.
  • cursor.rowcount shows how many rows were affected.
  • Always write the WHERE condition.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.