MySQL Database Connection Utility

  • Share this:

Code introduction


This function is used to connect to a MySQL database and print connection information. It accepts the database host, database name, username, and password as parameters. If the connection is successful, it will print the server version and the current database name.


Technology Stack : mysql-connector-python

Code Type : Function

Code Difficulty : Advanced


                
                    
import mysql.connector
from mysql.connector import Error

def connect_to_database(host, database, user, password):
    try:
        connection = mysql.connector.connect(
            host=host,
            database=database,
            user=user,
            password=password
        )
        if connection.is_connected():
            db_info = connection.get_server_info()
            print("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")