Q&A 3 🐍 How do you connect Python to MySQL/MariaDB?

3.1 Explanation

Once you’ve created a database and tables in MySQL/MariaDB, you can use Python to interact with them. This allows you to:

  • Run queries programmatically
  • Automate inserts, updates, and deletes
  • Integrate database results with pandas for analysis

We’ll use the official mysql-connector-python library, which works smoothly with XAMPP’s MariaDB.

βΈ»

3.2 Python Code (Using mysql-connector-python)

Install the connector (if not already installed):

pip install mysql-connector-python

Then create a simple connection and query:

import mysql.connector

# Establish connection
conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",       # default is empty in XAMPP
    database="cdi_learning"
)

# Create a cursor to run SQL commands
cursor = conn.cursor()

# Run a query
cursor.execute("SELECT * FROM students")

# Fetch and display results
print("Students table contents:")
for row in cursor.fetchall():
    print(row)

# Close connection
conn.close()
Students table contents:
(1, 'Alice Example', 'alice@example.com', datetime.date(2025, 8, 10))
(2, 'Bob Tester', 'bob@test.com', datetime.date(2025, 8, 11))

3.3 βœ… Learning Outcome

By the end of this Q&A, you will be able to:

  • Connect Python to a MySQL/MariaDB database using mysql-connector-python
  • Run SQL queries from Python and fetch results
  • Print query results in Python for inspection

3.4 🧠 Takeaway

SQL creates, Python orchestrates.
With a connector, you can automate queries, integrate results with analysis tools, and scale up your workflows.