SOURCE CODE
try:
import mysql.connector
except ModuleNotFoundError:
print("MySQL connector not found. Please install it by running 'pip install
mysql-connector-python'")
exit()
# Establish connection to MySQL
def connect_to_db():
return mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="ecommerce"
)
# Create tables if not exists
def create_tables():
db = connect_to_db()
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS items (
id INT AUTO_INCREMENT PRIMARY KEY,
category_id INT,
name VARCHAR(255),
price DECIMAL(10, 2),
FOREIGN KEY (category_id) REFERENCES categories(id)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS cart (
id INT AUTO_INCREMENT PRIMARY KEY,
item_id INT,
quantity INT,
FOREIGN KEY (item_id) REFERENCES items(id)
)
""")
db.commit()
db.close()
# Populate categories and items
def populate_data():
db = connect_to_db()
cursor = db.cursor()
categories = ["clothing", "electronics", "groceries", "games"]
items = {
"clothing": {"t shirt": 399, "jacket": 599, "socks": 99, "pyjama": 399,
"shirt": 299, "trouser": 499, "jean": 399, "kurti": 299, "top": 399},
"electronics": {
"vivo A12": 20000, "vivo v10_pro": 18000, "vivo z12": 47000, "iPhone
13": 59000, "iPhone 12": 55000,
"Realme K19": 21000, "Realme G7": 30000, "samsung galaxy S23":
45000, "samsung z flip": 60000,
"LG I20": 50000, "sony A11": 60000, "sony bravia42": 68000,
"micromax b12": 41000, "samsung xx39": 55000,
"apple macbook": 55000, "apple macpro": 65000, "vivo flipmax": 39000,
"Realme flipxx": 25000
},
"groceries": {"maggi": 14, "yippe": 10, "surfexl": 50, "bikaner bhujia": 15,
"haldiram bhujia": 20},
"games": {"minecraft": 2500, "fallout 4": 3000, "overwatch": 2000,
"fortnite": 1500, "pubg": 1000}
}
for category in categories:
cursor.execute("INSERT IGNORE INTO categories (name) VALUES
(%s)", (category,))
cursor.execute("SELECT * FROM categories")
category_data = {name: id for id, name in cursor.fetchall()}
for category, item_data in items.items():
for item, price in item_data.items():
cursor.execute("""
INSERT INTO items (category_id, name, price)
VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE price = %s
""", (category_data[category], item, price, price))
db.commit()
db.close()
# Add item to cart
def add_to_cart(item_name, category):
db = connect_to_db()
cursor = db.cursor()
cursor.execute("SELECT id FROM items WHERE name = %s",
(item_name,))
item = cursor.fetchone()
if item:
cursor.execute("INSERT INTO cart (item_id, quantity) VALUES (%s, %s)
ON DUPLICATE KEY UPDATE quantity = quantity + 1", (item[0], 1))
print(item_name + " added to cart under category " + category + ".")
else:
print("Item not found.")
db.commit()
db.close()
# Remove item from cart
def remove_from_cart(item_name):
db = connect_to_db()
cursor = db.cursor()
cursor.execute("SELECT id FROM items WHERE name = %s",
(item_name,))
item = cursor.fetchone()
if item:
cursor.execute("DELETE FROM cart WHERE item_id = %s", (item[0],))
print(item_name + " removed from cart.")
else:
print("Item not found in cart.")
db.commit()
db.close()
# View cart with tax calculation and sorted items
def view_cart():
db = connect_to_db()
cursor = db.cursor()
cursor.execute("""
SELECT i.name, c.quantity, i.price * c.quantity AS total
FROM cart c
JOIN items i ON c.item_id = i.id
ORDER BY total ASC
""")
results = cursor.fetchall()
total = 0
print("Your Cart (sorted by price):")
for name, quantity, price in results:
print(name + " x " + str(quantity) + " - Rs " + str(price))
total += price
tax = total * 0.07
grand_total = total + tax
print("Total (before tax): Rs " + str(total))
print("Tax (7%): Rs " + str(round(tax, 2)))
print("Grand Total (after tax): Rs " + str(round(grand_total, 2)))
db.close()
# Main function
create_tables()
populate_data()
ans = "y"
while ans == "y":
print("Enter 1 if you're looking for a category!")
print("Enter 2 if you want to view the cart!")
print("Enter 3 if you want to remove items from the cart!")
print("Enter 4 if you want to generate the bill!")
n = int(input("Enter the number: "))
if n == 1:
category = input("Enter category (e.g., clothing, electronics, groceries,
games): ").lower()
if category == "electronics":
print("****WE HAVE THE FOLLOWING ELECTRONICS*****")
print("smartphones, televisions, laptops")
ctg_elect = input("Enter the type of electronics you want
(smartphones/televisions/laptops): ").lower()
electronics_data = {
'smartphones': {'vivo A12': 20000, 'vivo v10_pro': 18000, 'vivo z12':
47000, 'iPhone 13': 59000, 'iPhone 12': 55000},
'television': {'LG I20': 50000, 'sony A11': 60000, 'sony bravia42':
68000, 'micromax b12': 41000},
'laptop': {'apple macbook': 55000, 'apple macpro': 65000, 'vivo
flipmax': 39000, 'Realme flipxx': 25000}
}
if ctg_elect == "smartphones":
print("****** Available smartphones ******")
for item, price in electronics_data['smartphones'].items():
print(f"{item} - Rs {price}")
item_name = input("Enter the smartphone you want to add to cart: ")
add_to_cart(item_name, "smartphones")
elif ctg_elect == "televisions":
print("****** Available televisions ******")
for item, price in electronics_data['television'].items():
print(f"{item} - Rs {price}")
item_name = input("Enter the television you want to add to cart: ")
add_to_cart(item_name, "televisions")
elif ctg_elect == "laptops":
print("****** Available laptops ******")
for item, price in electronics_data['laptop'].items():
print(f"{item} - Rs {price}")
item_name = input("Enter the laptop you want to add to cart: ")
add_to_cart(item_name, "laptops")
else:
print("ERROR! Item type not found. Please try again with correct
spelling.")
else:
print(f"Category '{category}' not found. Please choose again.")
elif n == 2:
view_cart()
elif n == 3:
item_name = input("Enter item name to remove: ")
remove_from_cart(item_name)
elif n == 4:
view_cart()
break
else:
print("Invalid choice. Try again.")
ans = input("Do you want to continue shopping or move to generate bill?
(y/n): ")
OUTPUTS
Use of 1
Use of 2
Use of 3
Use of 4