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):
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))