How do I connect to a MySQL Database in Python?

To connect to a MySQL database in Python, you can use the mysql-connector-python library. Here's an example of how to connect to a database and execute a simple query:

import mysql.connector

cnx = mysql.connector.connect(user='your_username', 
                              password='your_password',
                              host='your_host',
                              database='your_database')
cursor = cnx.cursor()

query = 'SELECT * FROM your_table'
cursor.execute(query)

for row in cursor:
    print(row)

cursor.close()
cnx.close()

Watch a course Python - The Practical Guide

You can also use the python sqlalchemy library to connect to a MySQL database.

from sqlalchemy import create_engine

engine = create_engine("mysql+mysqlconnector://{user}:{password}@{host}/{database}".format(
    user="your_username",
    password="your_password",
    host="your_host",
    database="your_database"
))

Make sure you have the mysql-connector-python library installed by running !pip install mysql-connector-python or !pip install sqlalchemy in the command line.