0% found this document useful (0 votes)
3 views19 pages

PYMYSQL3

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

PYMYSQL3

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

PYMYSQL (Assignment – 3)

Basic code for display, insert, search and delete


import pymysql as py

#creating database
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20')

cur = db1.cursor()

cur.execute("CREATE database IF NOT EXISTS bus ;")

#creating tables
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

cur.execute("CREATE TABLE IF NOT EXISTS product(Pcode VARCHAR(3),Pname


VARCHAR(10),Uprice INT,Rating SMALLINT,BID VARCHAR(3))")
cur.execute("CREATE TABLE IF NOT EXISTS brand(BID VARCHAR(3),Bname VARCHAR(20))")

#Viewing the table


def view(query):
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

cur.execute(query)
rows = cur.fetchall()
columns = [desc[0] for desc in cur.description]
col_width = [len(col) for col in columns]
for row in rows:
for i,val in enumerate(row):
col_width[i] = max(col_width[i],len(str(val)))

col_format = " | ".join(["{:<" + str(width) + "}" for width in col_width])


row_format = " | ".join(["{:<" + str(col_width[i]) + "}" for i in
range(len(col_width))])

print(col_format.format(*columns))
print("-" * (sum(col_width) + 3 * (len(columns)-1)))
for row in rows:
print(row_format.format(*[str(val) for val in row]))

#covert user input to null


def convert(value):
if value=='':
return None
elif value==str(value):
return value
else:
return int(value)

#Inserting rows
def insert(table):
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
while True:
if table=='p':
code = input("Enter product code:")
name = input("Enter product name:")
price = int(input("Enter price:"))
rating = int(input("Enter rating:"))
ID = input("Enter brand ID:")

query = "INSERT into product values (%s,%s,%s,%s,%s)"


cur.execute(query,(code,name,price,rating,ID))
db1.commit()
print("Record inserted successfully!")

elif table=='b':
ID = input("Enter brand ID:")
name = input("Enter brand name:")

query = "INSERT into brand values (%s,%s)"


cur.execute(query,(ID,name))
db1.commit()
print("Record inserted successfully!")

else:
print("INVALID INPUT\nExiting...")
break

restart = input("Do you want to insert another record?(y/n):")


if restart=='y':
pass
elif restart=='n':
print("Exiting...")
break
else:
print("INAVLID VALUE\nExiting...")
break
except py.Error as err:
print(f"failed to insert the record due to this error : {err}")

finally:
db1.close()

#updating a record
def update():
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
while True:
table = input("Enter table name which is to be updated(p/b):")
c = input("Enter product code/brand ID :")
f = input("Enter field name which is to updated:")
updt = input("Enter update:")
u = convert(updt)
if table=='p':
query = f"UPDATE product SET {f} = %s WHERE pcode = %s"
cur.execute(query,(u,c))
db1.commit()
print("Updated successfully!")
elif table=='b':
query = f"UPDATE brand SET {f} = %s WHERE BID = %s"
cur.execute(query,(u,c))
db1.commit()
print("Updated successfully!")
else:
print("There is no such table in this database\nExiting...")
break
restart = input("Do you want to update another record?(y/n):")
if restart=='y':
pass
elif restart=='n':
print("Exiting...")
break
else:
print("INAVLID VALUE\nExiting...")
break
except py.Error as err:
print(f"Updation failed due to this error : {err}")

finally:
db1.close()

#search a record
def search():
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
while True:
table = input("Select table(p/b):")
if table=='p':
srch = input("Enter product code to be searched:")
query = f"SELECT * from product WHERE pcode = '{srch}'"
view(query)
elif table=='b':
srch = input("Enter brand id to be searched:")
query = f"SELECT * from brand WHERE BID = '{srch}'"
view(query)
else:
print("INVALID INPUT\nExiting...")
break
restart = input("Do you want to search another record?(y/n):")
if restart=='y':
pass
elif restart=='n':
print("Exiting...")
break
else:
print("INAVLID VALUE\nExiting...")
break
except py.Error as err:
print(f"search failed due to this error : {err}")

finally:
db1.close()

#deleting a record
def delete():
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
while True:
table = input("Select table(p/b):")
if table=='p':
dlt = input("Enter product code which is to be deleted:")
cur.execute(f"DELETE from product WHERE pcode = '{dlt}'")
db1.commit()
print("Deleted successfully!")
elif table=='b':
dlt =input("Enter brand id which is to be deleted:")
cur.execute(f"DELETE from brand WHERE BID = '{dlt}'")
db1.commit()
print("Deleted successfully!")
else:
print("INVALID VALUE")

restart = input("Do you want to delete another record?(y/n):")


if restart=='y':
pass
elif restart=='n':
print("Exiting...")
break
else:
print("INAVLID VALUE\nExiting...")
break

except py.Error as err:


print(f"Deletion failed due to this error : {err}")

finally:
db1.close()

#MENU
while True:
print("""What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record""")
a = int(input("Enter here:"))

if a==1:
b = int(input("""Which table would you like to display?
1.Product
2.Brand
3.Both
Enter here:"""))
if b==1:
query = "SELECT * from product"
view(query)
elif b==2:
query = "SELECT * from brand"
view(query)
elif b==3:
query = "SELECT pcode,pname,uprice,rating,p.BID as brand_ID,bname
from product p,brand b WHERE p.BID = b.BID"
view(query)
else:
print("INVALID VALUE")
elif a==2:
c = input("Select table(p/b):")
insert(c)
elif a==3:
update()
elif a==4:
search()
elif a==5:
delete()
else:
print("INVALID VALUE GIVEN")

restart = input("Do you want to perform again?(y/n):")


if restart=='y':
pass
elif restart=='n':
print("Exiting...")
break
else:
print("INAVLID VALUE\nExiting...")
break
OUTPUT
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:2
Select table(p/b):p
Enter product code:P01
Enter product name:Shampoo
Enter price:120
Enter rating:6
Enter brand ID:M03
Record inserted successfully!
Do you want to insert another record?(y/n):y
Enter product code:P02
Enter product name:Toothpaste
Enter price:54
Enter rating:8
Enter brand ID:M02
Record inserted successfully!
Do you want to insert another record?(y/n):y
Enter product code:P03
Enter product name:Soap
Enter price:25
Enter rating:7
Enter brand ID:M03
Record inserted successfully!
Do you want to insert another record?(y/n):y
Enter product code:P04
Enter product name:Toothpaste
Enter price:65
Enter rating:4
Enter brand ID:M04
Record inserted successfully!
Do you want to insert another record?(y/n):y
Enter product code:P05
Enter product name:Soap
Enter price:38
Enter rating:5
Enter brand ID:M05
Record inserted successfully!
Do you want to insert another record?(y/n):y
Enter product code:P06
Enter product name:Shampoo
Enter price:245
Enter rating:6
Enter brand ID:M05
Record inserted successfully!
Do you want to insert another record?(y/n):n
Exiting...
Do you want to perform again?(y/n):y
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:2
Select table(p/b):b
Enter brand ID:M02
Enter brand name:Dantkanti
Record inserted successfully!
Do you want to insert another record?(y/n):y
Enter brand ID:M03
Enter brand name:Medimix
Record inserted successfully!
Do you want to insert another record?(y/n):y
Enter brand ID:M04
Enter brand name:Pepsodent
Record inserted successfully!
Do you want to insert another record?(y/n):y
Enter brand ID:M05
Enter brand name:Dove
Record inserted successfully!
Do you want to insert another record?(y/n):n
Exiting...
Do you want to perform again?(y/n):y
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:1
Which table would you like to display?
1.Product
2.Brand
3.Both
Enter here:1
Pcode | Pname | Uprice | Rating | BID
------------------------------------------
P01 | Shampoo | 120 | 6 | M03
P02 | Toothpaste | 54 | 8 | M02
P03 | Soap | 25 | 7 | M03
P04 | Toothpaste | 65 | 4 | M04
P05 | Soap | 38 | 5 | M05
P06 | Shampoo | 245 | 6 | M05
Do you want to perform again?(y/n):y
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:1
Which table would you like to display?
1.Product
2.Brand
3.Both
Enter here:2
BID | Bname
---------------
M02 | Dantkanti
M03 | Medimix
M04 | Pepsodent
M05 | Dove
Do you want to perform again?(y/n):y
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:1
Which table would you like to display?
1.Product
2.Brand
3.Both
Enter here:3
pcode | pname | uprice | rating | brand_ID | bname
-----------------------------------------------------------
P01 | Shampoo | 120 | 6 | M03 | Medimix
P02 | Toothpaste | 54 | 8 | M02 | Dantkanti
P03 | Soap | 25 | 7 | M03 | Medimix
P04 | Toothpaste | 65 | 4 | M04 | Pepsodent
P05 | Soap | 38 | 5 | M05 | Dove
P06 | Shampoo | 245 | 6 | M05 | Dove
Do you want to perform again?(y/n):y
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:3
Enter table name which is to be updated:product
Enter product code :P05
Enter field name which is to updated:uprice
Enter update:42

#ERROR OCCURED
Updation failed due to this error : (1054, "Unknown column 'P05' in 'where clause'")
Do you want to perform again?(y/n):n
Exiting...

#AFTER FIXING THE ERROR


What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:3
Enter table name which is to be updated(p/b):p
Enter product code :P05
Enter field name which is to updated:uprice
Enter update:42
Updated successfully!
Do you want to update another record?(y/n):n
Do you want to perform again?(y/n):y
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:4
Select table(p/b):p
Enter product code to be searched:P04
Pcode | Pname | Uprice | Rating | BID
------------------------------------------
P04 | Toothpaste | 65 | 4 | M04
Do you want to search another record?(y/n):y
Select table(p/b):b
Enter brand id to be searched:M03
BID | Bname
-------------
M03 | Medimix
Do you want to search another record?(y/n):n
Exiting...
Do you want to perform again?(y/n):y
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:5
Select table(p/b):p
Enter product code which is to be deleted:P06
Deleted successfully!
Do you want to delete another record?(y/n):n
Exiting...
Do you want to perform again?(y/n):y
What do you want to do?
1.Display the table
2.Insert a new record
3.Update record
4.search record
5.delete record
Enter here:2
Select table(p/b):p
Enter product code:P06
Enter product name:Shampoo
Enter price:245
Enter rating:6
Enter brand ID:M05
Record inserted successfully!
Do you want to insert another record?(y/n):n
Exiting...
Do you want to perform again?(y/n):n
Exiting...
QUESTIONS

1. Display the structure of the tables.

2. Display all the products brand wise.

3. List all the products with a rating above the average rating of all products.

4. Count products of each brand.

5. Fetch top “n” products based on their ratings, including brand names.

SOLUTIONS
1. CODE:-
def struc():
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
while True:
a = input("select table to display its structure(p/b):")
if a=='p':
query = "Describe product"
view(query)
elif a=='b':
query = "Describe brand"
view(query)
else:
print("INVALID VALUE\nExiting...")
break
restart = input("Do you want to perform again?(y/n):")
if restart=='y':
pass
elif restart=='n':
print("Exiting...")
break
else:
print("INAVLID VALUE\nExiting...")
break
except py.Error as err:
print(f"Error : {err}")
struc()

OUTPUT:-
select table to display its structure(p/b):p
Field | Type | Null | Key | Default | Extra
---------------------------------------------------
Pcode | varchar(3) | YES | | None |
Pname | varchar(10) | YES | | None |
Uprice | int | YES | | None |
Rating | smallint | YES | | None |
BID | varchar(3) | YES | | None |
Do you want to perform again?(y/n):y
select table to display its structure(p/b):b
Field | Type | Null | Key | Default | Extra
--------------------------------------------------
BID | varchar(3) | YES | | None |
Bname | varchar(20) | YES | | None |
Do you want to perform again?(y/n):n
Exiting...

2. CODE:-
def all_prods():
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
query = "SELECT b.bname , GROUP_CONCAT(p.pname) as products from product p
JOIN brand b ON p.bid = b.bid GROUP BY b.bname"
view(query)
except py.Error as err:
print(f"Error : {err}")
all_prods()

OUTPUT:-
bname | products
------------------------
Dantkanti | Toothpaste
Dove | Soap,Shampoo
Medimix | Shampoo,Soap
Pepsodent | Toothpaste

3. CODE:-
def prod():
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
cur.execute("SELECT avg(rating) from product")
avg = cur.fetchone()[0]
query2 = f"SELECT p.pname as product , b.bname as brand ,rating from product
p JOIN brand b ON p.bid=b.bid WHERE rating > {avg}"
view(query2)
except py.Error as err:
print(f"Error : {err}")
prod()

OUTPUT:-
product | brand | rating
-------------------------------
Toothpaste | Dantkanti | 8
Soap | Medimix | 7
4. CODE:-
def count_prod():
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
query2= "SELECT b.bname as Brand ,count(p.pname) as No_of_products from
product p JOIN brand b ON p.bid=b.bid GROUP BY b.bname"
view(query2)
except py.Error as err:
print(f"Error : {err}")
count_prod()

OUTPUT:-
Brand | No_of_products
--------------------------
Medimix | 2
Dantkanti | 1
Pepsodent | 1
Dove | 2

5. CODE:-
def top_prod():
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')

cur = db1.cursor()

try:
n = int(input("Enter n (value must not exceed no. of products):"))
cur.execute("SELECT * from product")
no_of_products = cur.fetchall()
if n<=len(no_of_products):
query = f"SELECT p.pname,b.bname,rating from product p JOIN brand b ON
p.bid=b.bid ORDER BY rating DESC LIMIT {n}"
view(query)
else:
print("Value exceeded no. of products\nExiting...")
except py.Error as err:
print(f"Error : {err}")
top_prod()

OUTPUT:-
Enter n (value must not exceed no. of products):3
pname | bname | rating
-------------------------------
Toothpaste | Dantkanti | 8
Soap | Medimix | 7
Shampoo | Medimix | 6

NAME – Sonal
CLASS – 12th B
ROLL NO - 33

You might also like