MySQL Database Connection Function

  • Share this:

Code introduction


This function uses the mysql-connector-python library to connect to a MySQL database. It takes the database's host, user, and password as parameters and returns a database connection object.


Technology Stack : mysql-connector-python

Code Type : Database Connection

Code Difficulty : Intermediate


                
                    
def connect_to_database(host, user, password):
    """
    Connects to a MySQL database using the provided credentials.
    """
    import mysql.connector
    try:
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password
        )
        print("Successfully connected to the database")
        return connection
    except mysql.connector.Error as err:
        print(f"Error connecting to MySQL: {err}")
        return None