Python MySQL Select Data

Read data from your tables - Find your information!

🔍 Get Data from Your Table!

Selecting data is like searching through your database to find information. Let's see all our students!


cursor.execute("SELECT * FROM students")
results = cursor.fetchall()

for student in results:
    print(student)
                                    
SELECT
Command
Easy
To Read
Fast
Results

What is Selecting Data?

Selecting data means:

  • 🔍 Finding information in your tables
  • 📖 Reading data you stored earlier
  • 📊 Getting results to show or use
  • 🎯 Searching for specific information

Get All Students

Simple Select All

import mysql.connector

# Connect to database
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='yourpass',
    database='my_school'
)

cursor = connection.cursor()

# Get all students
cursor.execute("SELECT * FROM students")
students = cursor.fetchall()

print("👥 All Students:")
for student in students:
    print(f"ID: {student[0]}, Name: {student[1]}, Age: {student[2]}")

cursor.close()
connection.close()

Different Ways to Get Data

📋

fetchall()

Gets ALL results at once

📄

fetchone()

Gets ONE result at a time

📊

fetchmany(5)

Gets 5 results at a time

Try Different Methods

import mysql.connector

connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='yourpass',
    database='my_school'
)

cursor = connection.cursor()

# Method 1: Get all at once
cursor.execute("SELECT name, age FROM students")
all_students = cursor.fetchall()
print("📋 All students:", all_students)

# Method 2: Get one at a time
cursor.execute("SELECT name, age FROM students")
first_student = cursor.fetchone()
print("👤 First student:", first_student)

# Method 3: Get 2 at a time
cursor.execute("SELECT name, age FROM students")
two_students = cursor.fetchmany(2)
print("👥 Two students:", two_students)

cursor.close()
connection.close()

Get Specific Information

Select Specific Columns

import mysql.connector

connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='yourpass',
    database='my_school'
)

cursor = connection.cursor()

# Get only names and emails
cursor.execute("SELECT name, email FROM students")
contacts = cursor.fetchall()

print("📧 Student Contacts:")
for contact in contacts:
    print(f"Name: {contact[0]}, Email: {contact[1]}")

cursor.close()
connection.close()

Make Results Easier to Read

Dictionary Results (Easier!)

import mysql.connector

connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='yourpass',
    database='my_school'
)

# Use dictionary cursor - much easier!
cursor = connection.cursor(dictionary=True)

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

print("👥 Students (Easy to read):")
for student in students:
    print(f"Name: {student['name']}")
    print(f"Age: {student['age']}")
    print(f"Email: {student['email']}")
    print("-" * 20)

cursor.close()
connection.close()

Count Your Data

Count Records

import mysql.connector

connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='yourpass',
    database='my_school'
)

cursor = connection.cursor()

# Count all students
cursor.execute("SELECT COUNT(*) FROM students")
total = cursor.fetchone()[0]

print(f"📊 Total students: {total}")

cursor.close()
connection.close()

Make It Super Easy

Easy Student Viewer

import mysql.connector

def show_all_students():
    """Simple function to show all students"""
    try:
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='yourpass',
            database='my_school'
        )
        
        cursor = connection.cursor(dictionary=True)
        cursor.execute("SELECT * FROM students")
        students = cursor.fetchall()
        
        if students:
            print("👥 All Students:")
            print("=" * 30)
            for student in students:
                print(f"🆔 ID: {student['id']}")
                print(f"👤 Name: {student['name']}")
                print(f"🎂 Age: {student['age']}")
                print(f"📧 Email: {student['email']}")
                print("-" * 20)
        else:
            print("📭 No students found!")
            
    except mysql.connector.Error as error:
        print(f"❌ Error: {error}")
        
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

# Use it like this:
show_all_students()

Safe Search (Very Important!)

Search Safely

import mysql.connector

def find_student_by_name(search_name):
    """Find student by name safely"""
    try:
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='yourpass',
            database='my_school'
        )
        
        cursor = connection.cursor(dictionary=True)
        
        # Safe way to search - use %s!
        cursor.execute("SELECT * FROM students WHERE name LIKE %s", 
                      (f"%{search_name}%",))
        
        students = cursor.fetchall()
        
        if students:
            print(f"🔍 Found {len(students)} student(s):")
            for student in students:
                print(f"👤 {student['name']} - {student['email']}")
        else:
            print(f"😞 No students found with name '{search_name}'")
            
    except mysql.connector.Error as error:
        print(f"❌ Error: {error}")
        
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

# Use it like this:
find_student_by_name("John")

Simple Tips

📋 Use fetchall()

For getting all results at once

📖 Use Dictionary Cursor

Makes results much easier to read

🛡️ Always Use %s

For safe searching with user input

🔍 Check if Empty

Always check if you got results

🧠 Quick Check

Which method gets all results at once?

Which cursor type makes results easier to read?