MySQL Database Connection Function

  • Share this:

Code introduction


This function connects to a MySQL database using the provided host, user, password, and database name. It returns the connection object if successful, or None if there is an error.


Technology Stack : mysql-connector-python

Code Type : Database Connection

Code Difficulty : Intermediate


                
                    
def connect_to_database(host, user, password, database):
    import mysql.connector
    try:
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database
        )
        return connection
    except mysql.connector.Error as e:
        print(f"Error connecting to MySQL database: {e}")
        return None