Random MySQL Connection Management in Python

  • Share this:

Code introduction


This code defines a function to generate random MySQL database connection information, creates a database connection, executes a query, and closes the connection.


Technology Stack : pymysql, random

Code Type : The type of code

Code Difficulty : Advanced


                
                    
import pymysql
import random

def random_connection_info(hosts):
    """
    This function generates a random connection information for a MySQL database.
    It randomly selects a host from the provided list and generates random port, user, and password.
    """
    host = random.choice(hosts)
    port = random.randint(3306, 65535)
    user = "user_" + str(random.randint(1000, 9999))
    password = "pass_" + str(random.randint(1000, 9999))
    
    return host, port, user, password

def create_connection(host, port, user, password):
    """
    This function creates a connection to a MySQL database using the provided connection information.
    """
    connection = pymysql.connect(host=host, port=port, user=user, password=password)
    return connection

def execute_query(connection, query):
    """
    This function executes a given SQL query on the provided database connection and returns the result.
    """
    with connection.cursor() as cursor:
        cursor.execute(query)
        result = cursor.fetchall()
        return result

def close_connection(connection):
    """
    This function closes the connection to the MySQL database.
    """
    connection.close()

# Usage example
hosts = ['localhost', '192.168.1.1', 'example.com']
host, port, user, password = random_connection_info(hosts)
connection = create_connection(host, port, user, password)
query_result = execute_query(connection, "SELECT * FROM users")
close_connection(connection)                
              
Tags: