ByteBoard Notes Notes

Delete a record from a MySQL table from Python

Computer Science XII · Experiment 28 of 29 · SQL

12-CSPython–SQL connectivity
Expt. No.28
Page No.56

Delete a record

Aim

To write a Python program that deletes the record of a student whose roll number is entered by the user and confirms it with rowcount.

Concepts used

Algorithm

  1. Input the roll number.
  2. Execute DELETE with a %s placeholder and call commit().
  3. Display whether a record was deleted, using rowcount.
  4. Display the remaining records.

Program

# Delete a record from Python import mysql.connector con = mysql.connector.connect(host="localhost", user="root",                              password="your_password", database="school")cur = con.cursor() roll = int(input("Enter the roll number to delete: "))cur.execute("DELETE FROM student WHERE rollno = %s", (roll,))con.commit()if cur.rowcount == 0:    print("No record found")else:    print(cur.rowcount, "record deleted") cur.execute("SELECT * FROM student")print("Remaining records:")for row in cur.fetchall():    print(row)con.close()

A marked line continues the line above it. In your file, write it on the same line.

Change your_password to your own MySQL password before you run it.

Table used

Table: student
+--------+-------+-------+
| rollno | name  | marks |
+--------+-------+-------+
|      1 | Asha  |    82 |
|      2 | Rohan |    67 |
|      3 | Kabir |    91 |
|      4 | Diya  |    76 |
|      5 | Neel  |    58 |
+--------+-------+-------+

Output

$ python pysql_delete.py
Enter the roll number to delete: 2 1 record deleted Remaining records: (1, 'Asha', 82) (3, 'Kabir', 91) (4, 'Diya', 76) (5, 'Neel', 58)

✓ Printed by running this program, not typed by hand.

Result

The record of roll number 2 (Rohan) was deleted, rowcount was 1, and the remaining four records were displayed.

Viva voce: what the examiner may ask

01Why is the value written as (roll,) with a comma?

The values must be a tuple; (roll) without the comma is just a number in brackets.

02How can you undo a delete before it is committed?

By calling con.rollback().

03What happens if the WHERE clause is left out of DELETE?

Every row in the table is deleted.

Variations for the lab test

  1. Ask "Are you sure? (y/n)" before deleting.
  2. Delete all students with marks below 60.
  3. Display the record before deleting it.
! Common mistake Writing (roll) instead of (roll,) raises an error, because the parameters must be a tuple or list.
Back to the 12-CS index