MySQL Database Connection Function

  • Share this:

Code introduction


This function uses the mysql-connector-python library to connect to a MySQL database and returns the connection object. If the connection fails, it returns None and prints the error message.


Technology Stack : mysql-connector-python

Code Type : Function

Code Difficulty : Intermediate


                
                    
def connect_to_database(host, user, password, database):
    import mysql.connector
    try:
        # Connect to the MySQL database using the provided credentials
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database
        )
        # If connection is successful, return the connection object
        return connection
    except mysql.connector.Error as error:
        # If there is an error, print the error message
        print(f"Error connecting to MySQL: {error}")
        return None

# JSON representation of the code