Q:

Delete a Record from the Database in Python

0

Program to delete record from Database using the id entered by the user.

Solution:

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.

Algorithm:

  • Step 1: Connect to the database using connect() method in pymysql.
  • Step 2: Get input of faculty ID from the user.
  • Step 3: Write a query to fetch the details of the faculty and display it to the user.
  • Step 4: Get confirmation input from the user.
  • Step 5: If 'Yes', deleted record.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python program to delete a Record from the Database

import  cpymysql 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....

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now