Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: DML Statements in MySQL

Python MySQL DML Statements - E-Commerce Guide

Learn how to manipulate data in MySQL from Python with an E-Commerce platform.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
Read Time: 12 minutes Level: Intermediate Case Study: E-Commerce Platform Focus: Python DML Implementation

E-Commerce Case Study: In this tutorial, you'll learn how to manipulate data in your E-Commerce platform using Python. You'll insert products, update orders, delete reviews, and query customer data.

Python Focus: This tutorial focuses on executing DML statements from Python using mysql-connector-python. For pure SQL DML reference and optimization, we have a separate MySQL DML Guide coming soon.

On this page:
  • What are DML Statements?
  • INSERT - Adding Data
  • UPDATE - Modifying Data
  • DELETE - Removing Data
  • SELECT - Reading Data
  • E-Commerce Python Examples
  • Best Practices
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • INSERT — adding products, customers, and orders
  • UPDATE — modifying prices, stock, and order status
  • DELETE — removing reviews and cancelled orders
  • SELECT — querying data for dashboards and reports
  • Python implementation — executing DML from Python

What are DML Statements?

DML (Data Manipulation Language) statements are used to add, modify, delete, and retrieve data from your database tables. They work with the data itself, not the structure.

INSERT

Adds new rows to a table

UPDATE

Modifies existing rows

DELETE

Removes rows from a table

SELECT

Retrieves data from tables

1

DML in E-Commerce

# ============================================================
# DML STATEMENTS IN E-COMMERCE
# ============================================================

# 1. INSERT - Add a new product
INSERT INTO products (product_name, price, stock_quantity) 
VALUES ('iPhone 15', 999.99, 50);

# 2. UPDATE - Change product price
UPDATE products SET price = 899.99 WHERE product_id = 1;

# 3. DELETE - Remove a cancelled order
DELETE FROM orders WHERE order_id = 5 AND status = 'cancelled';

# 4. SELECT - Get all electronics products
SELECT * FROM products WHERE category = 'Electronics';

Key point: DML statements work with the data in your tables. They are the most commonly used SQL operations.

Quick Check: What does DML stand for? (Answer: Data Manipulation Language)

INSERT - Adding Data

2

Inserting E-Commerce Data from Python

# ============================================================
# INSERT STATEMENTS FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. INSERT A SINGLE PRODUCT
# ============================================================

query = """
    INSERT INTO products (product_name, category, price, stock_quantity)
    VALUES (%s, %s, %s, %s)
"""
values = ("iPhone 15 Pro", "Electronics", 999.99, 50)

cursor.execute(query, values)
connection.commit()

print(f"Product added! ID: {cursor.lastrowid}")

# ============================================================
# 2. INSERT A CUSTOMER
# ============================================================

query = """
    INSERT INTO customers (first_name, last_name, email, phone, city)
    VALUES (%s, %s, %s, %s, %s)
"""
values = ("Rahul", "Sharma", "rahul@email.com", "9876543210", "Mumbai")

cursor.execute(query, values)
connection.commit()

print(f"Customer added! ID: {cursor.lastrowid}")

# ============================================================
# 3. INSERT AN ORDER
# ============================================================

query = """
    INSERT INTO orders (customer_id, total_amount, status)
    VALUES (%s, %s, %s)
"""
values = (1, 1099.98, 'pending')

cursor.execute(query, values)
order_id = cursor.lastrowid
connection.commit()

print(f"Order added! ID: {order_id}")

# ============================================================
# 4. INSERT ORDER ITEMS
# ============================================================

query = """
    INSERT INTO order_items (order_id, product_id, quantity, unit_price, total_price)
    VALUES (%s, %s, %s, %s, %s)
"""
items = [
    (order_id, 1, 1, 999.99, 999.99),
    (order_id, 7, 1, 69.99, 69.99)
]

cursor.executemany(query, items)
connection.commit()

print(f"Added {cursor.rowcount} order items")

# ============================================================
# 5. INSERT A REVIEW
# ============================================================

query = """
    INSERT INTO reviews (customer_id, product_id, rating, comment)
    VALUES (%s, %s, %s, %s)
"""
values = (1, 1, 5, "Amazing phone! Great battery life.")

cursor.execute(query, values)
connection.commit()

print(f"Review added! ID: {cursor.lastrowid}")

cursor.close()
connection.close()

INSERT key points:

  • INSERT INTO — specifies the table
  • VALUES — provides the data
  • executemany() — inserts multiple rows
  • lastrowid — gets the auto-generated ID

Quick Check: How do you get the ID of a newly inserted row? (Answer: cursor.lastrowid)

UPDATE - Modifying Data

3

Updating E-Commerce Data from Python

# ============================================================
# UPDATE STATEMENTS FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. UPDATE PRODUCT PRICE
# ============================================================

cursor.execute("""
    UPDATE products 
    SET price = 899.99 
    WHERE product_id = 1
""")
connection.commit()
print(f"Updated {cursor.rowcount} product(s)")

# ============================================================
# 2. UPDATE PRODUCT STOCK
# ============================================================

cursor.execute("""
    UPDATE products 
    SET stock_quantity = stock_quantity - 1 
    WHERE product_id = 1 AND stock_quantity > 0
""")
connection.commit()
print(f"Updated {cursor.rowcount} product(s)")

# ============================================================
# 3. UPDATE ORDER STATUS
# ============================================================

cursor.execute("""
    UPDATE orders 
    SET status = 'completed', payment_status = 'paid' 
    WHERE order_id = 1
""")
connection.commit()
print(f"Updated {cursor.rowcount} order(s)")

# ============================================================
# 4. UPDATE WITH CALCULATIONS
# ============================================================

# Apply 10% discount to electronics
cursor.execute("""
    UPDATE products 
    SET price = price * 0.90 
    WHERE category = 'Electronics' AND price > 500
""")
connection.commit()
print(f"Updated {cursor.rowcount} product(s)")

# ============================================================
# 5. UPDATE WITH PARAMETERIZED QUERY
# ============================================================

def update_customer_phone(customer_id, new_phone):
    query = "UPDATE customers SET phone = %s WHERE customer_id = %s"
    cursor.execute(query, (new_phone, customer_id))
    connection.commit()
    return cursor.rowcount

rows = update_customer_phone(1, "9876543211")
print(f"Updated {rows} customer(s)")

cursor.close()
connection.close()

UPDATE key points:

  • UPDATE table — specifies the table
  • SET column = value — defines the change
  • WHERE — specifies which rows to update
  • Always use WHERE — prevents updating all rows

Quick Check: What happens if you forget WHERE in UPDATE? (Answer: ALL rows in the table are updated)

DELETE - Removing Data

4

Deleting E-Commerce Data from Python

⚠️ WARNING: DELETE is permanent!

Always use WHERE clause and consider soft deletion (marking as deleted) for important data.

# ============================================================
# DELETE STATEMENTS FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. DELETE A REVIEW
# ============================================================

cursor.execute("DELETE FROM reviews WHERE review_id = 1")
connection.commit()
print(f"Deleted {cursor.rowcount} review(s)")

# ============================================================
# 2. DELETE CANCELLED ORDERS
# ============================================================

cursor.execute("DELETE FROM orders WHERE status = 'cancelled'")
connection.commit()
print(f"Deleted {cursor.rowcount} order(s)")

# ============================================================
# 3. DELETE WITH PARAMETERIZED QUERY
# ============================================================

def delete_order(order_id):
    query = "DELETE FROM orders WHERE order_id = %s"
    cursor.execute(query, (order_id,))
    connection.commit()
    return cursor.rowcount

rows = delete_order(5)
print(f"Deleted {rows} order(s)")

# ============================================================
# 4. SOFT DELETE - Mark as deleted instead of removing
# ============================================================

# Add a deleted flag to products table
cursor.execute("""
    ALTER TABLE products 
    ADD COLUMN is_deleted BOOLEAN DEFAULT 0
""")
connection.commit()
print("Added is_deleted column")

# Soft delete a product
cursor.execute("""
    UPDATE products 
    SET is_deleted = 1 
    WHERE product_id = 1
""")
connection.commit()
print(f"Soft deleted {cursor.rowcount} product(s)")

# Query that excludes soft-deleted products
cursor.execute("SELECT * FROM products WHERE is_deleted = 0")
products = cursor.fetchall()
print(f"Active products: {len(products)}")

cursor.close()
connection.close()

DELETE key points:

  • DELETE FROM table — specifies the table
  • WHERE — specifies which rows to delete
  • Always use WHERE — prevents deleting all rows
  • Soft delete — mark as deleted instead of removing

Quick Check: What is a soft delete? (Answer: Marking a record as deleted instead of actually removing it)

SELECT - Reading Data

5

Querying E-Commerce Data from Python

# ============================================================
# SELECT STATEMENTS FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. GET ALL PRODUCTS
# ============================================================

cursor.execute("SELECT * FROM products")
products = cursor.fetchall()

print("All Products:")
for p in products:
    print(f"  {p[1]} - ${p[4]} (Stock: {p[5]})")

# ============================================================
# 2. GET PRODUCTS BY CATEGORY
# ============================================================

cursor.execute("SELECT * FROM products WHERE category = 'Electronics'")
electronics = cursor.fetchall()

print("\nElectronics Products:")
for p in electronics:
    print(f"  {p[1]} - ${p[4]}")

# ============================================================
# 3. GET CUSTOMER ORDERS WITH DETAILS
# ============================================================

query = """
    SELECT o.order_id, o.order_date, o.total_amount, o.status,
           c.first_name, c.last_name
    FROM orders o
    JOIN customers c ON o.customer_id = c.customer_id
    WHERE c.customer_id = 1
    ORDER BY o.order_date DESC
"""
cursor.execute(query)
orders = cursor.fetchall()

print("\nCustomer Orders:")
for o in orders:
    print(f"  Order {o[0]} - {o[1]} - ${o[2]} - {o[3]}")

# ============================================================
# 4. GET TOP SELLING PRODUCTS
# ============================================================

cursor.execute("""
    SELECT p.product_name, SUM(oi.quantity) as total_sold,
           SUM(oi.quantity * oi.unit_price) as revenue
    FROM products p
    JOIN order_items oi ON p.product_id = oi.product_id
    GROUP BY p.product_id
    ORDER BY total_sold DESC
    LIMIT 5
""")
top_products = cursor.fetchall()

print("\nTop Selling Products:")
for p in top_products:
    print(f"  {p[0]} - {p[1]} units sold - ${p[2]} revenue")

# ============================================================
# 5. GET PRODUCT REVIEWS
# ============================================================

cursor.execute("""
    SELECT r.rating, r.comment, c.first_name, c.last_name
    FROM reviews r
    JOIN customers c ON r.customer_id = c.customer_id
    WHERE r.product_id = 1
    ORDER BY r.review_date DESC
""")
reviews = cursor.fetchall()

print("\nProduct Reviews:")
for r in reviews:
    print(f"  {'*' * r[0]} - {r[1][:50]}... - {r[2]} {r[3]}")

cursor.close()
connection.close()

SELECT key points:

  • SELECT columns — specifies what to retrieve
  • FROM table — specifies the source
  • WHERE — filters results
  • JOIN — combines related tables
  • ORDER BY — sorts results
  • LIMIT — limits number of results

Quick Check: What does JOIN do in a SELECT query? (Answer: It combines data from multiple related tables)

E-Commerce Python Examples

6

Complete E-Commerce Data Operations

# ============================================================
# COMPLETE E-COMMERCE DATA OPERATIONS
# ============================================================

import mysql.connector

class ECommerceData:
    """E-Commerce data operations using DML"""
    
    def __init__(self, db_config):
        self.db_config = db_config
        self.connection = None
        self.cursor = None
    
    def connect(self):
        try:
            self.connection = mysql.connector.connect(**self.db_config)
            self.cursor = self.connection.cursor()
            return True
        except Exception as e:
            print(f"Connection failed: {e}")
            return False
    
    # ============================================================
    # PRODUCT OPERATIONS
    # ============================================================
    
    def add_product(self, name, category, price, stock):
        """Add a new product"""
        query = """
            INSERT INTO products (product_name, category, price, stock_quantity)
            VALUES (%s, %s, %s, %s)
        """
        self.cursor.execute(query, (name, category, price, stock))
        self.connection.commit()
        return self.cursor.lastrowid
    
    def update_product_price(self, product_id, new_price):
        """Update product price"""
        query = "UPDATE products SET price = %s WHERE product_id = %s"
        self.cursor.execute(query, (new_price, product_id))
        self.connection.commit()
        return self.cursor.rowcount
    
    def update_product_stock(self, product_id, quantity_change):
        """Update product stock"""
        query = """
            UPDATE products 
            SET stock_quantity = stock_quantity + %s 
            WHERE product_id = %s AND stock_quantity + %s >= 0
        """
        self.cursor.execute(query, (quantity_change, product_id, quantity_change))
        self.connection.commit()
        return self.cursor.rowcount
    
    def get_products(self, category=None, min_price=None, max_price=None):
        """Get products with filters"""
        conditions = []
        params = []
        
        if category:
            conditions.append("category = %s")
            params.append(category)
        if min_price:
            conditions.append("price >= %s")
            params.append(min_price)
        if max_price:
            conditions.append("price <= %s")
            params.append(max_price)
        
        query = "SELECT * FROM products"
        if conditions:
            query += " WHERE " + " AND ".join(conditions)
        
        self.cursor.execute(query, params)
        return self.cursor.fetchall()
    
    # ============================================================
    # ORDER OPERATIONS
    # ============================================================
    
    def create_order(self, customer_id, items):
        """Create a new order with items"""
        self.connection.start_transaction()
        
        try:
            # Calculate total
            total = sum(item['price'] * item['quantity'] for item in items)
            
            # Create order
            query = """
                INSERT INTO orders (customer_id, total_amount, status)
                VALUES (%s, %s, 'pending')
            """
            self.cursor.execute(query, (customer_id, total))
            order_id = self.cursor.lastrowid
            
            # Add order items
            query = """
                INSERT INTO order_items (order_id, product_id, quantity, unit_price, total_price)
                VALUES (%s, %s, %s, %s, %s)
            """
            item_data = []
            for item in items:
                item_data.append((
                    order_id,
                    item['product_id'],
                    item['quantity'],
                    item['price'],
                    item['price'] * item['quantity']
                ))
            
            self.cursor.executemany(query, item_data)
            
            # Update stock
            for item in items:
                self.cursor.execute("""
                    UPDATE products 
                    SET stock_quantity = stock_quantity - %s 
                    WHERE product_id = %s
                """, (item['quantity'], item['product_id']))
            
            self.connection.commit()
            return {"success": True, "order_id": order_id}
            
        except Exception as e:
            self.connection.rollback()
            return {"success": False, "error": str(e)}
    
    def update_order_status(self, order_id, status):
        """Update order status"""
        query = "UPDATE orders SET status = %s WHERE order_id = %s"
        self.cursor.execute(query, (status, order_id))
        self.connection.commit()
        return self.cursor.rowcount
    
    def get_orders_by_customer(self, customer_id):
        """Get all orders for a customer"""
        query = """
            SELECT o.order_id, o.order_date, o.total_amount, o.status,
                   GROUP_CONCAT(CONCAT(p.product_name, ' (', oi.quantity, ')')) as items
            FROM orders o
            JOIN order_items oi ON o.order_id = oi.order_id
            JOIN products p ON oi.product_id = p.product_id
            WHERE o.customer_id = %s
            GROUP BY o.order_id
            ORDER BY o.order_date DESC
        """
        self.cursor.execute(query, (customer_id,))
        return self.cursor.fetchall()
    
    # ============================================================
    # REVIEW OPERATIONS
    # ============================================================
    
    def add_review(self, customer_id, product_id, rating, comment):
        """Add a product review"""
        query = """
            INSERT INTO reviews (customer_id, product_id, rating, comment)
            VALUES (%s, %s, %s, %s)
        """
        self.cursor.execute(query, (customer_id, product_id, rating, comment))
        self.connection.commit()
        return self.cursor.lastrowid
    
    def get_product_reviews(self, product_id):
        """Get all reviews for a product"""
        query = """
            SELECT r.rating, r.comment, c.first_name, c.last_name
            FROM reviews r
            JOIN customers c ON r.customer_id = c.customer_id
            WHERE r.product_id = %s
            ORDER BY r.review_date DESC
        """
        self.cursor.execute(query, (product_id,))
        return self.cursor.fetchall()
    
    # ============================================================
    # ANALYTICS OPERATIONS
    # ============================================================
    
    def get_sales_summary(self):
        """Get sales summary by category"""
        query = """
            SELECT p.category,
                   COUNT(DISTINCT o.order_id) as order_count,
                   SUM(oi.quantity) as units_sold,
                   SUM(oi.quantity * oi.unit_price) as revenue
            FROM products p
            JOIN order_items oi ON p.product_id = oi.product_id
            JOIN orders o ON oi.order_id = o.order_id
            WHERE o.status = 'completed'
            GROUP BY p.category
            ORDER BY revenue DESC
        """
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    def get_customer_summary(self):
        """Get customer summary"""
        query = """
            SELECT c.customer_id, c.first_name, c.last_name,
                   COUNT(o.order_id) as order_count,
                   COALESCE(SUM(o.total_amount), 0) as total_spent
            FROM customers c
            LEFT JOIN orders o ON c.customer_id = o.customer_id
            GROUP BY c.customer_id
            ORDER BY total_spent DESC
        """
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()

# ============================================================
# DEMONSTRATION
# ============================================================

db_config = {
    "host": "localhost",
    "user": "root",
    "password": "secret",
    "database": "ecommerce_db"
}

store = ECommerceData(db_config)

if store.connect():
    
    print("=" * 60)
    print("E-COMMERCE DATA OPERATIONS")
    print("=" * 60)
    
    # 1. Add a product
    print("\n1. ADDING PRODUCT")
    product_id = store.add_product("Wireless Mouse", "Electronics", 29.99, 100)
    print(f"Product added with ID: {product_id}")
    
    # 2. Update product
    print("\n2. UPDATING PRODUCT")
    rows = store.update_product_price(product_id, 24.99)
    print(f"Updated {rows} product(s)")
    
    # 3. Get products
    print("\n3. GETTING PRODUCTS")
    products = store.get_products(category="Electronics", max_price=50)
    print(f"Found {len(products)} electronics under $50:")
    for p in products:
        print(f"  {p[1]} - ${p[4]}")
    
    # 4. Create order
    print("\n4. CREATING ORDER")
    items = [
        {"product_id": product_id, "quantity": 2, "price": 24.99}
    ]
    result = store.create_order(1, items)
    print(f"Order result: {result}")
    
    # 5. Get customer orders
    print("\n5. CUSTOMER ORDERS")
    orders = store.get_orders_by_customer(1)
    for o in orders:
        print(f"  Order {o[0]} - ${o[2]} - {o[3]}")
        print(f"    Items: {o[4]}")
    
    # 6. Sales summary
    print("\n6. SALES SUMMARY")
    sales = store.get_sales_summary()
    for s in sales:
        print(f"  {s[0]}: {s[1]} orders, {s[2]} units, ${s[3]} revenue")
    
    store.close()

This example shows:

  • All DML operations in one class
  • Transaction management for complex operations
  • Error handling with rollback
  • Analytics queries for business insights
  • Customer and order management

Quick Check: Why use transactions for order creation? (Answer: To ensure all operations succeed or none do, preventing data inconsistency)

Best Practices

7

DML Best Practices

# ============================================================
# DML BEST PRACTICES
# ============================================================

print("1. ALWAYS USE WHERE CLAUSE")
print("   - In UPDATE and DELETE statements")
print("   - Prevents accidental mass updates/deletions")

print("\n2. USE PARAMETERIZED QUERIES")
print("   - Always use %s placeholders")
print("   - Protects against SQL injection")

print("\n3. USE TRANSACTIONS FOR RELATED OPERATIONS")
print("   - Group INSERT, UPDATE, DELETE together")
print("   - Commit or rollback as a unit")

print("\n4. CHECK ROW COUNT")
print("   - Use cursor.rowcount to verify operations")
print("   - Confirm expected number of rows affected")

print("\n5. USE SOFT DELETE WHEN POSSIBLE")
print("   - Add is_deleted column")
print("   - Update instead of delete for important data")

print("\n6. VALIDATE DATA BEFORE INSERT/UPDATE")
print("   - Check data types and constraints")
print("   - Prevent errors at database level")

print("\n7. USE BATCH OPERATIONS FOR MULTIPLE ROWS")
print("   - Use executemany() for multiple inserts")
print("   - Better performance")

print("\n8. LOG DML OPERATIONS")
print("   - Track who changed what")
print("   - Useful for auditing and debugging")

Summary of best practices:

  • Always use WHERE — prevent mass updates/deletions
  • Parameterized queries — prevent SQL injection
  • Transactions — group related operations
  • Check rowcount — verify operations worked
  • Soft delete — recoverable deletion
  • Validate data — catch errors early

Quick Check: What is the most important rule for UPDATE and DELETE? (Answer: Always include a WHERE clause)

Try It Yourself

Experiment with DML statements in the editor below.

Loading Pyodide... 0%
Python Code Editor
========================================
DML STATEMENTS - PRACTICE
========================================

1. INSERT OPERATIONS
----------------------------------------
Added product: Sony Headphones (ID: 4)
Added product: Levi's Jeans (ID: 5)

2. SELECT OPERATIONS
----------------------------------------
All products:
iPhone 15 Pro - $999.99 (Stock: 50)
MacBook Air - $1099.99 (Stock: 20)
Nike Air Max - $149.99 (Stock: 100)
Sony Headphones - $299.99 (Stock: 45)
Levi's Jeans - $69.99 (Stock: 150)

Electronics products:
iPhone 15 Pro - $999.99
MacBook Air - $1099.99
Sony Headphones - $299.99

3. UPDATE OPERATIONS
----------------------------------------
Updated product 3 price to $129.99
Product 10 not found

4. DELETE OPERATIONS
----------------------------------------
Deleted product 2
Product 10 not found

5. TRANSACTION - CREATE ORDER
----------------------------------------
Order 1 created
Order 1 created successfully

6. FINAL PRODUCTS
----------------------------------------
iPhone 15 Pro - $999.99 (Stock: 48)
Nike Air Max - $129.99 (Stock: 100)
Sony Headphones - $299.99 (Stock: 45)
Levi's Jeans - $69.99 (Stock: 150)

7. DML SUMMARY
----------------------------------------
┌─────────────────┬──────────────────────────────────────────────┐
│ DML Statement │ Purpose │
├─────────────────┼──────────────────────────────────────────────┤
│ INSERT │ Add new data │
│ UPDATE │ Modify existing data │
│ DELETE │ Remove data │
│ SELECT │ Retrieve data │
└─────────────────┴──────────────────────────────────────────────┘

DML statements manipulate your E-Commerce data!
🏆

You've Got It!

You now understand DML statements in MySQL from Python. You can INSERT, UPDATE, DELETE, and SELECT data for your E-Commerce platform.

Quick Quiz

Test what you've learned:

1. What does INSERT do?
2. What must you use with UPDATE and DELETE?
3. How do you get the ID of a newly inserted row?
4. What is a soft delete?
5. Why use transactions for related operations?

Frequently Asked Questions

What is the difference between DML and DDL? ▼

DML manipulates data (INSERT, UPDATE, DELETE, SELECT). DDL defines structure (CREATE, ALTER, DROP). DML works with data; DDL works with structure.

Why should I use parameterized queries? ▼

Parameterized queries prevent SQL injection attacks. They separate SQL code from data, making it impossible for malicious input to change the query structure.

What is a common interview question about DML? ▼

Common questions include: "Explain the difference between DML and DDL," "What is the difference between DELETE and TRUNCATE?" and "How do you insert multiple rows in Python?"

What is the difference between DELETE and TRUNCATE? ▼

DELETE removes rows one by one (can use WHERE, can be rolled back). TRUNCATE removes all rows at once (faster, cannot use WHERE, resets AUTO_INCREMENT).

Will this conflict with future pure MySQL tutorials? ▼

No. This tutorial focuses on executing DML from Python with mysql-connector. Future MySQL tutorials will focus on SQL syntax and optimization with different titles and URLs.

Where to Go From Here

Now that you understand DML statements, check out these related topics:

Subqueries

Learn how to use subqueries for complex data retrieval.

Learn More →

JOIN Operations

Learn how to combine data from multiple tables.

Learn More →

Aggregation

Learn how to summarize data with GROUP BY.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: DDL Statements Next: Subqueries →