MySQL Database Connection with mysql-connector-python

  • Share this:

Code introduction


This function connects to a MySQL database using mysql-connector-python and returns a cursor object for executing SQL commands.


Technology Stack : mysql-connector-python

Code Type : Database connection function

Code Difficulty : Intermediate


                
                    
import mysql.connector
from mysql.connector import Error

def connect_to_database(host, database, user, password):
    """
    Connect to a MySQL database using mysql-connector-python.
    
    Parameters:
    - host (str): The hostname or IP address of the MySQL server.
    - database (str): The name of the database to connect to.
    - user (str): The username to use for authentication.
    - password (str): The password to use for authentication.
    
    Returns:
    - cursor: A cursor object used to execute SQL commands.
    """
    try:
        connection = mysql.connector.connect(host=host,
                                             database=database,
                                             user=user,
                                             password=password)
        if connection.is_connected():
            return connection.cursor()
    except Error as e:
        print("Error while connecting to MySQL", e)

# JSON representation of the function