Random MySQL Database Connection with pymysql

  • Share this:

Code introduction


This function uses the pymysql library to connect to a MySQL database and returns a cursor object, randomly selecting a database to connect to from the provided list.


Technology Stack : pymysql, MySQL database connection

Code Type : Database connection function

Code Difficulty : Intermediate


                
                    
import pymysql
import random

def random_select_database_connection(host, user, password, db, charset='utf8mb4'):
    """
    Connect to a MySQL database and return a cursor object.
    The function randomly selects a database to connect to from the provided list.
    """
    connection = pymysql.connect(host=host, user=user, password=password, db=db, charset=charset)
    cursor = connection.cursor()
    return cursor