PYMYSQL3
PYMYSQL3
#creating database
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20')
cur = db1.cursor()
#creating tables
db1 = py.connect(host = 'localhost' ,
user = 'root',
passwd = 'Sejal@20',
db = 'bus')
cur = db1.cursor()
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)))
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]))
#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:")
elif table=='b':
ID = input("Enter brand ID:")
name = input("Enter brand name:")
else:
print("INVALID INPUT\nExiting...")
break
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")
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")
#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...
3. List all the products with a rating above the average rating of all products.
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