Connecting to MySQL in Python

Python: How to Connect to MySQL

To connect to a MySQL database in Python, you can use the mysql-connector-python library. You can install it using pip:

pip install mysql-connector-python

Once installed, you can connect to a MySQL database by specifying the host, user, password, and database name:

import mysql.connector

# database configurations
config = {
    "host": "localhost",
    "user": "root",
    "password": "",
    "database": "scratchpad"
}

if __name__ == '__main__':

    try:

        # create a context manager for the database connection
        with mysql.connector.connect(**config) as db:

            # create a cursor object
            with db.cursor(dictionary=True) as cursor:
                
                # execute a SELECT query
                query = "SELECT * FROM users"
                cursor.execute(query)

                # fetch the results
                users = cursor.fetchall()

                # print the results
                for user in users:
                    print(user["id"], user["name"], user["email"])

    except mysql.connector.Error as error:
        
        # handle any errors that occur during execution
        print("Error occurred: {}".format(error))
        

The code above demonstrates how to connect to a MySQL database using Python’s mysql.connector module and fetch data from a table. I hope you find this code helpful!

If you wish to learn more about Python, please subscribe to our newsletter today and continue your Python learning journey with us!

Scroll to Top