0% found this document useful (0 votes)
2 views

PROGRAM1

The document contains a Python script that connects to a MySQL server to create a database named 'MuffinHouse' and four tables: menu_items, customers, orders, and order_items. Each table is defined with specific fields and relationships, including foreign keys. The script handles connection errors and ensures the MySQL connection is closed after operations are completed.

Uploaded by

Durga Praveen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PROGRAM1

The document contains a Python script that connects to a MySQL server to create a database named 'MuffinHouse' and four tables: menu_items, customers, orders, and order_items. Each table is defined with specific fields and relationships, including foreign keys. The script handles connection errors and ensures the MySQL connection is closed after operations are completed.

Uploaded by

Durga Praveen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

import mysql.

connector
from mysql.connector import Error

def create_db_and_tables():
try:
# Connect to MySQL server
connection = mysql.connector.connect(
host='localhost',
user='root',
password='Arya@123'
)

if connection.is_connected():
print("Connected to MySQL server")

cursor = connection.cursor()

# Create database if it doesn't exist


cursor.execute("CREATE DATABASE IF NOT EXISTS MuffinHouse")
cursor.execute("USE MuffinHouse")

# Create tables
cursor.execute("""
CREATE TABLE IF NOT EXISTS menu_items (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL
)
""")

cursor.execute("""
CREATE TABLE IF NOT EXISTS customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
phone VARCHAR(20)
)
""")

cursor.execute("""
CREATE TABLE IF NOT EXISTS orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
total DECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES customers(id)
)
""")

cursor.execute("""
CREATE TABLE IF NOT EXISTS order_items (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT,
menu_item_id INT,
quantity INT,
FOREIGN KEY (order_id) REFERENCES orders(id),
FOREIGN KEY (menu_item_id) REFERENCES menu_items(id)
)
""")

print("Database and tables created successfully")


except Error as e:
print(f"Error: {e}")

finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection closed")

if __name__ == "__main__":
create_db_and_tables()

You might also like