ADVERTISEMENT
ADVERTISEMENT

Python program to delete a record from database using its ID (Example 2)

Here, we will see a Python program to delete a record from the database using an ID entered by the user.
Submitted by Shivang Yadav, on March 06, 2021

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 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', delete the record and print "Record Deleted".

Program to delete a record from database using its ID

import pymysql as MYSQL
try:
 conn=MYSQL.connect(host='localhost',port=3306,
    user='root',password='123',db='practice')

 cmd=conn.cursor()

 id=input("Enter Product Id U Want to Delete:")

 q="select * from products where productid={}".format(id)
 cmd.execute(q)

 row=cmd.fetchone()
 if(row==None):
     print("Record Not Found")
 else:
     #print(row)
    print("Product Id:",row[0])
    print("Product Name:",row[1])
    print("Product Price:",row[2])
    print("Product Date:",row[3])
    ch=input("Are U Sure Yes/No?")
    if(ch.lower()=='yes'):
     q="delete from products where productid={}".format(id)
     cmd.execute(q)
     print("Record Deleted....")

 conn.commit()
 conn.close()
except Exception as e:
    print(e)

Output:

Enter Product Id U Want to Delete:47
Product ID:47
Product Name:cPhone Prime
Product Price:12499
Product Date: 27/10/2020
Are U Sure yes/no?yes
Record Deleted...

Python database (SQL/MySQL) programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.