Python MySQL Get Started

Your first steps with Python and MySQL - Super easy!

🚀 Hello MySQL!

MySQL is like a smart filing cabinet for your data. Python can talk to MySQL to save and find information easily!


import mysql.connector

# Connect to MySQL
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='your_password'
)
print("Connected! 🎉")
                                    
Easy
To Learn
3
Steps
Fun
To Use

What is MySQL?

MySQL is like a super organized notebook that can:

  • 📝 Store lots of information (like names, ages, emails)
  • 🔍 Find information quickly
  • 🔒 Keep your data safe
  • Work very fast

Step 1: Install MySQL Connector

Install Command

pip install mysql-connector-python

💡 What This Does

This installs a special tool that lets Python talk to MySQL databases.

Step 2: Connect to MySQL

Your First Connection

import mysql.connector

# Connect to MySQL
connection = mysql.connector.connect(
    host='localhost',      # Where MySQL is running
    user='root',          # Your username
    password='yourpass'   # Your password
)

print("✅ Connected to MySQL!")
connection.close()
print("🔒 Connection closed")

Step 3: Test Your Connection

Safe Connection Test

import mysql.connector

try:
    # Try to connect
    connection = mysql.connector.connect(
        host='localhost',
        user='root',
        password='yourpass'
    )
    
    print("✅ Success! MySQL is working!")
    
    # Get MySQL version
    cursor = connection.cursor()
    cursor.execute("SELECT VERSION()")
    version = cursor.fetchone()
    print(f"📊 MySQL version: {version[0]}")
    
except mysql.connector.Error as error:
    print(f"❌ Oops! Error: {error}")
    
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("🔒 Closed connection")

Understanding Connection Parts

🏠

host

Where MySQL lives
'localhost' = your computer

👤

user

Your MySQL username
Usually 'root'

🔑

password

Your MySQL password
Keep it secret!

Make It Even Easier

Simple Helper Function

import mysql.connector

def connect_to_mysql():
    """Simple function to connect to MySQL"""
    try:
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='yourpass'
        )
        print("✅ Connected!")
        return connection
    except mysql.connector.Error as error:
        print(f"❌ Connection failed: {error}")
        return None

# Use it like this:
my_connection = connect_to_mysql()

if my_connection:
    print("🎉 Ready to work with MySQL!")
    my_connection.close()
else:
    print("😞 Could not connect")

🎯 What You Learned

✅ Installed Connector

Added the tool to connect Python and MySQL

✅ Made Connection

Connected Python to your MySQL database

✅ Tested It

Made sure everything works correctly

✅ Ready for More

Now you can create databases and tables!

💡 Quick Tips for Beginners

  • Always close connections: Use connection.close()
  • Use try/except: Catches errors safely
  • Change the password: Use your actual MySQL password
  • Start simple: Get connection working first!

🧠 Quick Check

What do you need to install to use MySQL with Python?

What does 'localhost' mean?