MySQL Database Connection and Info Retrieval

  • Share this:

Code introduction


This function connects to a MySQL database using mysql-connector-python and retrieves the database version and name. It includes steps to connect to the database, execute queries, and close the connection.


Technology Stack : mysql-connector-python

Code Type : 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(f"Connected to MySQL Server version {db_info}")
            cursor = connection.cursor()
            cursor.execute("SELECT DATABASE();")
            record = cursor.fetchone()
            print(f"Database: {record[0]}")
    except Error as e:
        print(f"Error: {e}")
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL connection is closed")