Delete a Record from MySQL Table in Python

Python MySQL | Delete Record: In this tutorial, we will learn how to delete a record from the MySQL table using Python program? By Shivang Yadav Last updated : April 21, 2023

We will use Python's pymysql library to work with the database. This library provides the programmer the functionality to run MySQL query using python.

How to Delete a Record from MySQL Table in Python?

The following steps are used to delete a record from MySQL table:

  1. Inmport the MySQL connect using import statement.
    import pymysql as mysql
  2. Connect to the database using connect() method in pymysql.
    conn=mysql.connect(host='localhost',port=3306,user='root',password='123',db='myschool')
    cmd=conn.cursor()
  3. Get input of faculty ID from the user.
    id=input("Enter Faculty Id U Want To Delete:")
  4. Write a query to fetch the details of the faculty and display it to the user.
    q="select * from faculties where fid='{}'".format(id)
  5. Get confirmation input from the user.
  6. If 'Yes', deleted record.
    q="delete from faculties where fid={}".format(id)
    cmd.execute(q)

Python Program to Delete a Record from MySQL Table

import pymysql as mysql

try:
    conn=mysql.connect(host='localhost',port=3306,user='root',password='123',db='myschool')
    cmd=conn.cursor()
    
    id=input("Enter Faculty Id U Want To Delete:")
    
    q="select * from faculties where fid='{}'".format(id)
    cmd.execute(q)
    
    row=cmd.fetchone()
    
    if(row==None):
        print("Not Found")
    else:
        print("ID:",row[0])
        print("Name:", row[1])
        print("Birth Date:", row[2])
        print("Department:", row[3])
        print("Salary:", row[4])
        
        ch=input("Are you Sure(yes/no)?")
        if(ch=='yes'):
            q="delete from faculties where fid={}".format(id)
            cmd.execute(q)
            conn.commit()
            print("Record Deleted....")
    conn.close()

except Exception as e:
    print("Error:",e)

Output

Enter Faculty Id U Want To Delete: 03
ID: 03
Name: John
Birth Data: 12.4.1988
Department: computer Science
Salary: 45000
Are you Sure(yes/no)?yes
Record Deleted....

Python MySQL Programs »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.