import mysql.
connector
# Import MySQL connector for connecting Python with MySQL
from mysql.connector import Error
# Import error handling for MySQL
# Database configuration - specify database connection details here
db_config = {
'host': 'localhost', # MySQL server address
'user': 'root', # MySQL username
'password': 'tiger', # MySQL password
'database': 'product_db' # Database name
}
# Connect to the database
def create_connection():
try:
# Establish a connection to MySQL with provided configuration
connection = mysql.connector.connect(**db_config)
if connection.is_connected():
print("Connected to MySQL database")
return connection
except Error as e:
# Handle connection errors
print(f"Error: {e}")
return None
# Create a table for products
def create_table(connection):
try:
cursor = connection.cursor()
# Create a cursor object for executing SQL queries
# SQL statement to create a products table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS products (
id INT AUTO_INCREMENT PRIMARY KEY, # Primary key, auto-incrementing ID
name VARCHAR(255) NOT NULL, # Product name (string)
price DECIMAL(10, 2) NOT NULL, # Product price (decimal with 2 digits after
decimal)
quantity INT NOT NULL # Product quantity (integer)
)
""")
connection.commit()
# Commit changes to the database
print("Table 'products' created successfully.")
except Error as e:
# Handle errors during table creation
print(f"Error: {e}")
# Add a new product
def add_product(connection, name, price, quantity):
try:
cursor = connection.cursor()
# Create a cursor object
# SQL statement to insert a new product record into the table
sql = "INSERT INTO products (name, price, quantity) VALUES (%s, %s, %s)"
cursor.execute(sql, (name, price, quantity))
# Execute with parameters
connection.commit()
# Commit changes
print(f"Product '{name}' added successfully.")
except Error as e:
# Handle errors during record insertion
print(f"Error: {e}")
# View all products
def view_products(connection):
try:
cursor = connection.cursor()
# Create a cursor object
cursor.execute("SELECT * FROM products")
# Execute SQL to fetch all product records
rows = cursor.fetchall()
# Fetch all rows from the query result
print("Product List:")
print("ID | Name | Price | Quantity")
print("-" * 30)
for row in rows:
print(row)
# Print each product record
except Error as e:
# Handle errors during data retrieval
print(f"Error: {e}")
# Update a product
def update_product(connection, product_id, name=None, price=None, quantity=None):
try:
cursor = connection.cursor()
# Create a cursor object
updates = []
# List to hold parts of the update statement
params = []
# List to hold parameter values
# Check which fields need to be updated
if name:
updates.append("name = %s")
params.append(name)
if price:
updates.append("price = %s")
params.append(price)
if quantity:
updates.append("quantity = %s")
params.append(quantity)
# Add product ID as the last parameter
params.append(product_id)
# Formulate the final SQL update query
sql = f"UPDATE products SET {', '.join(updates)} WHERE id = %s"
cursor.execute(sql, params)
# Execute update with parameters
connection.commit()
# Commit changes
# Check if the product was updated
if cursor.rowcount > 0:
print("Product updated successfully.")
else:
print("Product not found.")
except Error as e:
# Handle errors during the update
print(f"Error: {e}")
# Delete a product
def delete_product(connection, product_id):
try:
cursor = connection.cursor()
# Create a cursor object
# SQL statement to delete a product by ID
sql = "DELETE FROM products WHERE id = %s"
cursor.execute(sql, (product_id,))
# Execute delete with parameter
connection.commit() # Commit changes
# Check if the product was deleted
if cursor.rowcount > 0:
print("Product deleted successfully.")
else:
print("Product not found.")
except Error as e:
# Handle errors during deletion
print(f"Error: {e}")
# CLI Menu to display options to the user
def menu():
print("\n[[[[[[[[[[[[[[[< Product Database Management System >]]]]]]]]]]]]]]]")
print("1. Add a new product")
print("2. View all products")
print("3. Update a product")
print("4. Delete a product")
print("5. Exit")
choice = input("Choose an option (1-5): ")
return choice
# Main application
def main():
# Establish database connection
connection = create_connection()
if connection is None:
print("Failed to connect to database. Exiting...")
return
create_table(connection)
# Create products table if not exists
# Main loop to process user choices
while True:
choice = menu()
if choice == '1':
# Add a new product
name = input("Enter product name: ")
price = float(input("Enter product price: "))
quantity = int(input("Enter product quantity: "))
add_product(connection, name, price, quantity)
elif choice == '2':
# View all products
view_products(connection)
elif choice == '3':
# Update a product
product_id = int(input("Enter product ID to update: "))
name = input("Enter new name (leave blank to skip): ")
price = input("Enter new price (leave blank to skip): ")
quantity = input("Enter new quantity (leave blank to skip): ")
# Convert inputs to None if they are blank
name = name if name else None
price = float(price) if price else None
quantity = int(quantity) if quantity else None
update_product(connection, product_id, name, price, quantity)
elif choice == '4':
# Delete a product
product_id = int(input("Enter product ID to delete: "))
delete_product(connection, product_id)
elif choice == '5':
# Exit the application
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
connection.close() # Close the database connection
if __name__ == "__main__":
main()
# Run the main function if the script is executed directly