Connecting to MySQL Database with PyMySQL

  • Share this:

Code introduction


This function uses the PyMySQL library to connect to a MySQL database and returns a connection object. If the connection is successful, it prints a message; if the connection fails, it prints an error message.


Technology Stack : PyMySQL

Code Type : Database Connection Function

Code Difficulty : Intermediate


                
                    
import pymysql
import random

def connect_to_database(host, user, password, database):
    """
    Connect to a MySQL database using PyMySQL.
    """
    try:
        connection = pymysql.connect(host=host, user=user, password=password, database=database)
        print("Connected to the database successfully")
        return connection
    except pymysql.MySQLError as e:
        print(f"Error connecting to MySQL database: {e}")
        return None                
              
Tags: