Connecting to MySQL Database with mysql-connector-python

  • Share this:

Code introduction


This function connects to a MySQL database using mysql-connector-python and prints the database version and name.


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.
    """
    try:
        connection = mysql.connector.connect(host=host,
                                             database=database,
                                             user=user,
                                             password=password)
        if connection.is_connected():
            db_info = connection.get_server_info()
            print("Successfully connected to MySQL Server version", db_info)
            cursor = connection.cursor()
            cursor.execute("SELECT DATABASE();")
            record = cursor.fetchone()
            print("You're connected to database:", record)
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL connection is closed")

# JSON Explanation