Connecting Python with MySQL


Step-by-Step Guide to Connect Python with MySQL

1. Install MySQL Connector

Run the following command in your terminal or command prompt:

pip install mysql-connector-python

2. Import the Connector

import mysql.connector

3. Connect to MySQL Server

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="your_password",  # Replace with your actual MySQL password
    database="your_database"   # Optional at this step
)

Success Check:

if conn.is_connected():
    print("Connected to MySQL!")

4. Create a Database

cursor = conn.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS demo_db")
print("Database created successfully!")

5. Create a Table

Switch to the database first:

conn.database = "demo_db"

Then:

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

6. Insert Data into Table

sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
values = ("John Doe", "john@example.com")
cursor.execute(sql, values)
conn.commit()

print(cursor.rowcount, "record inserted.")

7. Read Data from Table

cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()

for row in rows:
    print(row)

8. Update Data

sql = "UPDATE users SET email = %s WHERE name = %s"
val = ("john.doe@demo.com", "John Doe")
cursor.execute(sql, val)
conn.commit()

9. Delete Data

sql = "DELETE FROM users WHERE name = %s"
val = ("John Doe",)
cursor.execute(sql, val)
conn.commit()

10. Close the Connection

cursor.close()
conn.close()

Bonus: Use Environment Variables for Credentials (Security Best Practice)

Use Python's os module or .env files (with python-dotenv) to keep your MySQL credentials secure instead of hardcoding them.

Use Cases

  • Web development (e.g., Flask/Django apps)
  • Data analytics pipelines
  • Backend APIs
  • Automated scripts with persistent data