Connecting Python with MySQL

Connecting Python with MySQL allows you to interact with a MySQL database directly from your Python applications.

You can:

Insert data
Fetch records
Update data
Delete records
Build backend applications

This is commonly used in:

Web development
Data engineering
Automation scripts
Backend APIs

Step 1: Install MySQL Connector

Install the official MySQL connector:

pip install mysql-connector-python

Step 2: Import and Connect to Database

Example:

import mysql.connectorconnection = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="your_database"
)print("Connected successfully!")

If connection is successful, Python is now connected to MySQL.

Step 3: Create a Cursor

Cursor allows you to execute SQL queries.

cursor = connection.cursor()

Step 4: Execute SQL Query

Example: Create a table

cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
)
""")

Step 5: Insert Data

query = "INSERT INTO users (name, email) VALUES (%s, %s)"
values = ("Ali", "ali@email.com")cursor.execute(query, values)
connection.commit()print("Data inserted successfully!")

Important:

Always use parameterized queries (%s) to prevent SQL injection.

Step 6: Fetch Data

cursor.execute("SELECT * FROM users")
results = cursor.fetchall()for row in results:
print(row)

You can also use:

fetchone() → Single record
fetchmany(n) → Multiple records

Step 7: Update Data

query = "UPDATE users SET name = %s WHERE id = %s"
values = ("Ahmed", 1)cursor.execute(query, values)
connection.commit()

Step 8: Delete Data

query = "DELETE FROM users WHERE id = %s"
values = (1,)cursor.execute(query, values)
connection.commit()

Step 9: Close Connection

Always close connections to free resources.

cursor.close()
connection.close()

Handling Errors

Use try-except block:

import mysql.connector
from mysql.connector import Errortry:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="your_database"
)
print("Connected successfully!")except Error as e:
print("Error:", e)

Best Practices

Use parameterized queries
Close connections properly
Handle exceptions
Use connection pooling for large applications
Never hardcode sensitive credentials

Real-World Use Case

Web Application:

User submits form
Python backend stores data in MySQL
Data retrieved and displayed on dashboard

This integration is fundamental in backend development.

Key Takeaway

Connecting Python with MySQL enables powerful database operations directly from Python applications.

By using mysql-connector, parameterized queries, and proper error handling, you can build secure and scalable database-driven systems.

Home » PYTHON FOR DATA ENGINEERING (PYDE) > SQL and Databases with Python > Connecting Python with MySQL