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: Introduction to MySQL with Python

Python MySQL - Introduction to Database Programming

Learn how to connect Python with MySQL databases.

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.
On this page:
  • What is a Database?
  • Why Use MySQL with Python?
  • How Python Talks to MySQL
  • What You Can Do with Python and MySQL
  • Real-World Example
  • Best Practices
  • Try It Yourself
  • Quick Quiz
  • Frequently Asked Questions
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • What is a database — storing and organizing data
  • Why use MySQL with Python — power of Python + reliability of MySQL
  • How they work together — Python connects to MySQL, sends queries, gets results
  • What you can build — web apps, data analysis, automation
  • Real-world example — see it in action

What is a Database?

A database is a organized collection of data that's stored and accessed electronically. Think of it like a digital filing cabinet where you can store, find, and manage information.

Imagine you have a notebook where you write down all your contacts — names, phone numbers, email addresses. That's like a simple database. Now imagine you have thousands of contacts and you need to quickly find everyone who lives in a certain city. That's where a proper database shines.

MySQL is one of the most popular databases in the world. It's used by companies like Facebook, Twitter, and YouTube. It's free, reliable, and works great with Python.

💡 Key concept: A database is a structured way to store data. MySQL is a database management system that helps you create, read, update, and delete data efficiently.

Why Use MySQL with Python?

1

A Powerful Combination

Python and MySQL are a perfect match. Here's why developers love this combination.

# Why Use MySQL with Python?

print("=" * 50)
print("WHY USE MYSQL WITH PYTHON?")
print("=" * 50)

# ============================================================
# THE POWER OF PYTHON + MYSQL
# ============================================================

print("\n1. WHY THIS COMBINATION WORKS")

print("""
┌─────────────────────────────────────────────────────────────────────┐
│ WHY PYTHON + MYSQL IS A GREAT CHOICE                               │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  PYTHON:                                                           │
│  • Easy to learn and use                                           │
│  • Huge ecosystem of libraries                                     │
│  • Great for web development, data science, automation             │
│  • Active community                                                │
│                                                                     │
│  MYSQL:                                                            │
│  • Reliable and proven (used by major companies)                   │
│  • Free and open-source                                            │
│  • Fast and efficient                                              │
│  • Works on all platforms (Windows, Mac, Linux)                    │
│                                                                     │
│  TOGETHER:                                                         │
│  • Build powerful web applications                                 │
│  • Analyze large datasets                                          │
│  • Automate data processing                                        │
│  • Store and retrieve data efficiently                             │
└─────────────────────────────────────────────────────────────────────┘
""")


# ============================================================
# REAL-WORLD USE CASES
# ============================================================

print("\n2. REAL-WORLD USE CASES")

print("""
┌─────────────────────┬─────────────────────────────────────────────────────┐
│ USE CASE            │ EXAMPLE                                            │
├─────────────────────┼─────────────────────────────────────────────────────┤
│ Web Applications    │ Django, Flask, FastAPI apps with user data        │
│ E-commerce          │ Product catalogs, orders, customers                │
│ Data Analysis       │ Analyzing sales data, customer behavior            │
│ Automation          │ Automated reports, data pipelines                 │
│ Content Management  │ Blogs, CMS systems with articles and users         │
│ APIs                │ REST APIs that serve data to frontend              │
│ Business Apps       │ Inventory management, CRM, ERP                    │
└─────────────────────┴─────────────────────────────────────────────────────┘
""")

print("\n   Python + MySQL is used in production by:")
print("   • Thousands of startups and companies")
print("   • Data-driven applications")
print("   • Web applications (Django, Flask)")
print("   • Data analysis and reporting tools")

Why MySQL with Python:

  • Powerful combo — Python's ease + MySQL's reliability
  • Free and open — both are free to use
  • Proven — used by Facebook, Twitter, YouTube
  • Versatile — web apps, data analysis, automation

Quick Check: What's one reason to use MySQL with Python? (Answer: Python is easy to use and MySQL is reliable, making them a great combination)

How Python Talks to MySQL

2

The Connection Process

Python doesn't talk to MySQL directly. It uses a driver or connector — a library that acts as a translator between Python and MySQL.

# How Python Talks to MySQL

print("=" * 50)
print("HOW PYTHON TALKS TO MYSQL")
print("=" * 50)

# ============================================================
# THE BIG PICTURE
# ============================================================

print("\n1. THE BIG PICTURE")

print("""
┌─────────────────────────────────────────────────────────────────────┐
│ HOW IT WORKS                                                       │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  1. Python connects to MySQL using a driver (connector)            │
│  2. Python sends SQL queries to MySQL                              │
│  3. MySQL executes the queries                                      │
│  4. MySQL sends results back to Python                             │
│  5. Python processes the results                                   │
│                                                                     │
│  Python ---------> MySQL Driver ---------> MySQL Database          │
│           SQL Query                      Execute                    │
│                                                                     │
│  Python <--------- MySQL Driver <--------- MySQL Database          │
│           Results                       Results                    │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
""")


# ============================================================
# POPULAR MYSQL DRIVERS FOR PYTHON
# ============================================================

print("\n2. POPULAR MYSQL DRIVERS FOR PYTHON")

print("""
┌─────────────────────────────┬─────────────────────────────────────────────┐
│ DRIVER                      │ DESCRIPTION                                │
├─────────────────────────────┼─────────────────────────────────────────────┤
│ mysql-connector-python      │ Official MySQL driver (recommended)        │
│ (mysql.connector)           │ Pure Python, no external dependencies      │
│                             │                                             │
│ PyMySQL                     │ Popular third-party driver                 │
│                             │ Lightweight, pure Python                   │
│                             │                                             │
│ mysqlclient                 │ Fast C-based driver                        │
│                             │ Faster than pure Python drivers            │
│                             │                                             │
│ SQLAlchemy                  │ ORM (Object Relational Mapper)             │
│                             │ Higher-level abstraction                   │
│                             │ Works with multiple databases              │
└─────────────────────────────┴─────────────────────────────────────────────┘

Installing mysql-connector-python:
    pip install mysql-connector-python

Installing PyMySQL:
    pip install pymysql
""")


# ============================================================
# BASIC CONNECTION PROCESS
# ============================================================

print("\n3. BASIC CONNECTION PROCESS")

print("""
import mysql.connector

# 1. Create a connection
connection = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password",
    database="your_database"
)

# 2. Create a cursor (the tool that sends queries)
cursor = connection.cursor()

# 3. Send a query
cursor.execute("SELECT * FROM users")

# 4. Get the results
results = cursor.fetchall()

# 5. Process the results
for row in results:
    print(row)

# 6. Close the connection
cursor.close()
connection.close()
""")

print("   This is the basic pattern you'll use for all database operations!")


# ============================================================
# THE CURSOR EXPLAINED
# ============================================================

print("\n4. THE CURSOR EXPLAINED")

print("""
A cursor is like a pointer that moves through the result set.

Think of it like reading a book:
- The cursor is your finger pointing to the current line
- fetchone() reads one row and moves the finger down
- fetchall() reads all remaining rows

Methods:
    cursor.execute(query)     - Send a query
    cursor.fetchone()         - Get one row
    cursor.fetchall()         - Get all rows
    cursor.fetchmany(n)       - Get n rows
    cursor.close()            - Close the cursor
""")

How Python talks to MySQL key points:

  • Driver — a library that connects Python to MySQL
  • Connection — the link between Python and MySQL
  • Cursor — the tool that sends queries and gets results
  • Query — the SQL command you send
  • Result — the data MySQL returns

Quick Check: What is a cursor used for in database programming? (Answer: It sends queries to the database and retrieves results)

What You Can Do with Python and MySQL

3

Building Real-World Applications

With Python and MySQL, you can build almost any type of application that needs to store data.

# What You Can Do with Python and MySQL

print("=" * 50)
print("WHAT YOU CAN DO WITH PYTHON AND MYSQL")
print("=" * 50)

# ============================================================
# WEB APPLICATIONS
# ============================================================

print("\n1. WEB APPLICATIONS")

print("""
Build dynamic websites with user accounts, data, and content:

    • User registration and login
    • Profile management
    • Blog posts and comments
    • Product catalogs
    • Shopping carts and orders
    • Content management systems

Frameworks that work great with MySQL:
    • Django (includes ORM)
    • Flask (with SQLAlchemy or MySQL connector)
    • FastAPI (with SQLAlchemy)
""")


# ============================================================
# DATA ANALYSIS AND REPORTING
# ============================================================

print("\n2. DATA ANALYSIS AND REPORTING")

print("""
Analyze data stored in MySQL using Python's data tools:

    • Generate reports and dashboards
    • Analyze sales and customer data
    • Create data visualizations
    • Build data pipelines
    • Export data to CSV, Excel, JSON

Tools you can use:
    • Pandas (read SQL queries)
    • Matplotlib and Seaborn (visualizations)
    • Jupyter Notebooks (interactive analysis)
""")


# ============================================================
# AUTOMATION AND TOOLS
# ============================================================

print("\n3. AUTOMATION AND TOOLS")

print("""
Automate tasks that involve database operations:

    • Automated backups
    • Data migration scripts
    • Scheduled reports
    • Data cleaning and validation
    • ETL (Extract, Transform, Load) pipelines

Example:
    - Export data from MySQL to CSV every day at midnight
    - Clean and transform data
    - Send reports via email
""")


# ============================================================
# API DEVELOPMENT
# ============================================================

print("\n4. API DEVELOPMENT")

print("""
Build REST APIs that serve data from MySQL:

    • CRUD operations (Create, Read, Update, Delete)
    • Data validation and security
    • Authentication and authorization
    • Serve data to web and mobile apps

Framework examples:
    • Flask-RESTful
    • FastAPI
    • Django REST Framework
""")


# ============================================================
# WHAT YOU'LL LEARN IN THIS SERIES
# ============================================================

print("\n5. WHAT YOU'LL LEARN IN THIS SERIES")

print("""
┌─────────────────────────────────────────────────────────────────────┐
│ IN THIS MYSQL WITH PYTHON SERIES                                   │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  • DBMS vs File System (Understanding the difference)              │
│  • Connecting to MySQL (Making the connection)                    │
│  • Creating Databases (Creating and managing databases)            │
│  • Creating Tables (Defining table structures)                    │
│  • Inserting Data (Adding records)                                │
│  • Selecting Data (Querying and retrieving data)                  │
│  • WHERE Clause (Filtering results)                               │
│  • Updating Data (Modifying records)                              │
│  • Deleting Data (Removing records)                               │
│  • Parameterized Queries (Preventing SQL injection)               │
│  • Transactions (ACID operations)                                 │
│  • Error Handling (Handling database errors)                      │
│  • Joins (Combining tables)                                       │
│  • Aggregation (Grouping and summarizing)                         │
│  • Best Practices (Writing clean database code)                   │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
""")

What you can do key points:

  • Web apps — user accounts, content management
  • Data analysis — reports, dashboards, insights
  • Automation — backups, data pipelines
  • APIs — serve data to frontend apps

Quick Check: What can you build with Python and MySQL? (Answer: Web applications, data analysis tools, automation scripts, APIs, and more)

Real-World Example

4

A Simple User Management System

# Real-World Example: User Management System

print("=" * 60)
print("USER MANAGEMENT SYSTEM")
print("=" * 60)

# This is a simulation of what you can build with Python and MySQL
# We'll use Python lists to simulate database tables

# ============================================================
# SIMULATED DATABASE TABLES
# ============================================================

# Simulating a 'users' table
users_table = [
    {"id": 1, "username": "alice", "email": "alice@example.com", "age": 30},
    {"id": 2, "username": "bob", "email": "bob@example.com", "age": 25},
    {"id": 3, "username": "charlie", "email": "charlie@example.com", "age": 35}
]

# Simulating a 'products' table
products_table = [
    {"id": 1, "name": "Laptop", "price": 999.99, "stock": 5},
    {"id": 2, "name": "Phone", "price": 699.99, "stock": 10},
    {"id": 3, "name": "Headphones", "price": 149.99, "stock": 20}
]

# Simulating an 'orders' table
orders_table = []


# ============================================================
# DATABASE OPERATIONS (Simulated)
# ============================================================

class DatabaseSimulator:
    """Simulate database operations"""
    
    def __init__(self):
        self.users = users_table.copy()
        self.products = products_table.copy()
        self.orders = orders_table.copy()
        self.next_user_id = len(users_table) + 1
        self.next_order_id = 1
    
    def get_all_users(self):
        """SELECT * FROM users"""
        print("   📋 Fetching all users...")
        return self.users
    
    def get_user_by_id(self, user_id):
        """SELECT * FROM users WHERE id = ?"""
        print(f"   🔍 Finding user with ID {user_id}...")
        for user in self.users:
            if user["id"] == user_id:
                return user
        return None
    
    def add_user(self, username, email, age):
        """INSERT INTO users (username, email, age) VALUES (?, ?, ?)"""
        print(f"   ➕ Adding user: {username}...")
        new_user = {
            "id": self.next_user_id,
            "username": username,
            "email": email,
            "age": age
        }
        self.users.append(new_user)
        self.next_user_id += 1
        return new_user
    
    def update_user(self, user_id, **kwargs):
        """UPDATE users SET ... WHERE id = ?"""
        print(f"   ✏️ Updating user {user_id}...")
        for user in self.users:
            if user["id"] == user_id:
                for key, value in kwargs.items():
                    if key in user:
                        user[key] = value
                return user
        return None
    
    def delete_user(self, user_id):
        """DELETE FROM users WHERE id = ?"""
        print(f"   🗑️ Deleting user {user_id}...")
        for i, user in enumerate(self.users):
            if user["id"] == user_id:
                del self.users[i]
                return True
        return False
    
    def create_order(self, user_id, product_id, quantity):
        """INSERT INTO orders (user_id, product_id, quantity) VALUES (?, ?, ?)"""
        print(f"   📦 Creating order for user {user_id}...")
        
        # Find the product
        product = None
        for p in self.products:
            if p["id"] == product_id:
                product = p
                break
        
        if not product:
            print(f"   ❌ Product {product_id} not found")
            return None
        
        # Check stock
        if product["stock"] < quantity:
            print(f"   ❌ Not enough stock for {product['name']}")
            return None
        
        # Create order
        order = {
            "id": self.next_order_id,
            "user_id": user_id,
            "product_id": product_id,
            "product_name": product["name"],
            "quantity": quantity,
            "total_price": product["price"] * quantity
        }
        self.orders.append(order)
        self.next_order_id += 1
        
        # Update stock
        product["stock"] -= quantity
        
        return order


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

print("\n1. CREATING THE DATABASE CONNECTION")
db = DatabaseSimulator()
print("   ✅ Database simulator ready")

print("\n2. FETCHING ALL USERS")
users = db.get_all_users()
for user in users:
    print(f"   User {user['id']}: {user['username']} ({user['email']}) - Age: {user['age']}")

print("\n3. FETCHING A SPECIFIC USER")
user = db.get_user_by_id(2)
if user:
    print(f"   Found: {user['username']} - {user['email']}")

print("\n4. ADDING A NEW USER")
new_user = db.add_user("diana", "diana@example.com", 28)
print(f"   Added: {new_user}")

print("\n5. UPDATING A USER")
updated = db.update_user(1, email="alice_new@example.com", age=31)
if updated:
    print(f"   Updated: {updated}")

print("\n6. FETCHING ALL USERS (After changes)")
users = db.get_all_users()
for user in users:
    print(f"   User {user['id']}: {user['username']} ({user['email']}) - Age: {user['age']}")

print("\n7. CREATING AN ORDER")
order = db.create_order(1, 1, 2)
if order:
    print(f"   Order created: {order}")

print("\n8. CHECKING PRODUCT STOCK")
for product in db.products:
    print(f"   {product['name']}: {product['stock']} in stock")

print("\n9. DELETING A USER")
db.delete_user(4)
print("   User 4 deleted")

print("\n10. FINAL USER LIST")
users = db.get_all_users()
for user in users:
    print(f"   User {user['id']}: {user['username']}")

print("\n" + "=" * 60)
print("KEY TAKEAWAYS:")
print("=" * 60)
print("""
- Python and MySQL work together to store and manage data
- You can perform CRUD operations (Create, Read, Update, Delete)
- This is what real applications do with databases
- The code is clean and easy to understand
- You can build anything from simple tools to complex applications
""")

Real-world example key points:

  • CRUD operations — Create, Read, Update, Delete
  • User management — add, update, delete users
  • Order processing — create orders, update stock
  • Data retrieval — fetch and display data

Quick Check: What are the four basic database operations? (Answer: Create, Read, Update, Delete — also known as CRUD)

Best Practices

5

Writing Good Database Code

# Best Practices for MySQL with Python

print("=" * 60)
print("BEST PRACTICES")
print("=" * 60)

# ============================================================
# 1. ALWAYS CLOSE YOUR CONNECTIONS
# ============================================================

print("\n1. ALWAYS CLOSE YOUR CONNECTIONS")

print("""
# Good - use context managers (with statement)
import mysql.connector

def get_users():
    with mysql.connector.connect(
        host="localhost",
        user="root",
        password="password",
        database="mydb"
    ) as connection:
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM users")
            return cursor.fetchall()
    # Connection and cursor are automatically closed

# Also good - manual cleanup
def get_users_manual():
    connection = mysql.connector.connect(...)
    cursor = connection.cursor()
    try:
        cursor.execute("SELECT * FROM users")
        return cursor.fetchall()
    finally:
        cursor.close()
        connection.close()
""")


# ============================================================
# 2. USE PARAMETERIZED QUERIES (Prevent SQL Injection)
# ============================================================

print("\n2. USE PARAMETERIZED QUERIES")

print("""
# Good - using parameterized queries
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))

# Also good - using %s with tuple
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", (name, email))

# Bad - string concatenation (SQL injection risk!)
cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")
""")


# ============================================================
# 3. USE CONTEXT MANAGERS
# ============================================================

print("\n3. USE CONTEXT MANAGERS")

print("""
# Good - with statement ensures cleanup
with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM users")
    results = cursor.fetchall()

# Bad - manual cleanup (easy to forget)
cursor = connection.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
cursor.close()  # Easy to forget!
""")


# ============================================================
# 4. HANDLE ERRORS
# ============================================================

print("\n4. HANDLE ERRORS")

print("""
# Good - handle database errors
try:
    cursor.execute("SELECT * FROM users")
    results = cursor.fetchall()
except mysql.connector.Error as e:
    print(f"Database error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

# Bad - no error handling
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
""")


# ============================================================
# 5. USE TRANSACTIONS
# ============================================================

print("\n5. USE TRANSACTIONS")

print("""
# Good - use transactions for multiple operations
try:
    cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
    cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
    connection.commit()  # Only commit if both succeed
except Exception:
    connection.rollback()  # Rollback if anything fails

# Bad - no transaction (inconsistent state if one fails)
cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
""")


# ============================================================
# 6. SUMMARY
# ============================================================

print("\n" + "=" * 60)
print("BEST PRACTICES SUMMARY")
print("=" * 60)
print("""
- Always close connections (use context managers)
- Use parameterized queries (prevent SQL injection)
- Use with statements for automatic cleanup
- Handle errors properly
- Use transactions for multiple operations
- Don't hardcode credentials (use environment variables)
- Use connection pooling for multiple requests
- Index your database tables
- Test your database code
- Use ORM for complex applications (SQLAlchemy)
""")

Best practices summary:

  • Close connections — always clean up
  • Parameterized queries — prevent SQL injection
  • Use context managers — automatic cleanup
  • Handle errors — gracefully handle database errors
  • Use transactions — for multiple operations

Quick Check: Why should you use parameterized queries? (Answer: To prevent SQL injection attacks)

Try It Yourself

Experiment with database operations in the editor below.

Loading Pyodide... 0%
Python Code Editor
==================================================
PYTHON MYSQL - INTRODUCTION PRACTICE
==================================================

1. SIMULATED DATABASE
Students table:
{'id': 1, 'name': 'Alice', 'grade': 'A', 'age': 20}
{'id': 2, 'name': 'Bob', 'grade': 'B', 'age': 22}
{'id': 3, 'name': 'Charlie', 'grade': 'C', 'age': 21}

2. SIMULATED CRUD OPERATIONS
Getting all students:
{'id': 1, 'name': 'Alice', 'grade': 'A', 'age': 20}
{'id': 2, 'name': 'Bob', 'grade': 'B', 'age': 22}
{'id': 3, 'name': 'Charlie', 'grade': 'C', 'age': 21}

Adding a new student:
Added: {'id': 4, 'name': 'Diana', 'grade': 'A', 'age': 19}

Getting student with ID 2:
Found: {'id': 2, 'name': 'Bob', 'grade': 'B', 'age': 22}

Updating student 2:
Updated: {'id': 2, 'name': 'Bob', 'grade': 'A+', 'age': 23}

All students after updates:
{'id': 1, 'name': 'Alice', 'grade': 'A', 'age': 20}
{'id': 2, 'name': 'Bob', 'grade': 'A+', 'age': 23}
{'id': 3, 'name': 'Charlie', 'grade': 'C', 'age': 21}
{'id': 4, 'name': 'Diana', 'grade': 'A', 'age': 19}
🏆

You've Got It!

You now understand the basics of working with MySQL in Python. You know why databases are important, how Python connects to MySQL, and what you can build.

Quick Quiz

Test what you've learned:

1. What is a database?
2. What is MySQL?
3. What is a cursor used for?
4. What does CRUD stand for?
5. Why should you use parameterized queries?

Frequently Asked Questions

What is MySQL? ▼

MySQL is a popular open-source relational database management system (RDBMS). It's used by companies like Facebook, Twitter, and YouTube to store and manage data. It's free, reliable, and works great with Python.

How does Python connect to MySQL? ▼

Python connects to MySQL using a driver or connector library. Popular options include mysql-connector-python (official), PyMySQL, and mysqlclient. These libraries handle the communication between Python and MySQL.

What is SQL injection and how do I prevent it? ▼

SQL injection is a security vulnerability where an attacker can inject malicious SQL code into your queries. Prevent it by always using parameterized queries. Never use string concatenation to build SQL queries.

Do I need to install MySQL to use Python with MySQL? ▼

Yes, you need to have MySQL installed on your system (or a remote MySQL server) to connect Python to a MySQL database. You also need to install a MySQL driver for Python (like mysql-connector-python).

What kind of applications can I build with Python and MySQL? ▼

You can build web applications (Django, Flask), data analysis tools, automation scripts, APIs, e-commerce platforms, content management systems, inventory management, CRM systems, and many other data-driven applications.

Is MySQL free? ▼

Yes, MySQL is free and open-source under the GPL license. There are also commercial versions with additional features, but the free version is sufficient for most applications.

Where to Go From Here

Now that you understand the basics, check out these related topics:

DBMS vs File System

Learn why databases are better than files for storing data.

Learn More →

Connecting to MySQL

Learn how to connect Python to a MySQL database.

Learn More →

Create Database

Learn how to create databases in MySQL.

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: Best Practices Assignments Next: DBMS vs File System →