0% found this document useful (0 votes)
13 views3 pages

Python SQL 5.delete

Uploaded by

throwawayy4700
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

Python SQL 5.delete

Uploaded by

throwawayy4700
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Python with MySQL (Database connectivity)

DATE: 18/10/2024

S.No. NAME OF PRACTICAL

Write a program to connect Python with MySQL using database connectivity and
perform the following operations on data in database BookShop and table Book.

5 DELETE THE DATA


SOUR
import mysql.connector as ms
CE
CODE
def print_table(cur):
cur.execute('SELECT * FROM book')
data = cur.fetchall()

bookno = 'BookNo'.ljust(10)
bookname = 'BookName'.ljust(50)
price = 'Price'.ljust(10)
author = 'Author'.ljust(30)
publisher = 'Publisher'.ljust(30)

print(bookno, bookname, price, author, publisher)


print('-' * 150)

for i in data:
print(
str(i[0]).ljust(10),
i[1].ljust(50),
str(i[2]).ljust(10),
i[3].ljust(30),
i[4].ljust(30)
)

def delete():
conn = ms.connect(
host='localhost',
user='root',
password='root',
database='bookshop'
)
cur = conn.cursor()

while True:
cur.execute('USE bookshop')
choice = int(input('''Choose an option:
1. Delete the whole record
2. Delete selected record
3. Exit
Enter your choice: '''))

if choice == 1:
cur.execute('DELETE FROM book')
print("All records deleted.")
conn.commit()

elif choice == 2:
record_id = int(input("Enter the ID of the record
to delete: "))
cur.execute('DELETE FROM book WHERE
BookNo = %s', (record_id,))
conn.commit()

print('Record with ID {}
deleted.'.format(record_id))

elif choice == 3:
print('Exiting')
break

else:
print("Invalid choice. Please try again.")
continue

print_table(cur)

cont = input("Do you want to continue deleting


records? (yes/no): ")
if cont.lower() != 'yes':
break

cur.close()
conn.close()

delete()

OUTP
UT

You might also like