Python MySQL Database Connection, Query, and Closure

  • Share this:

Code introduction


This code defines a Python function that can connect to a MySQL database, execute a query, and close the connection. The function first generates random database connection information, then attempts to connect to the database, executes a query, and returns the query results.


Technology Stack : The package and technology stack used in this code include pymysql for MySQL database connection and interaction.

Code Type : Function

Code Difficulty : Advanced


                
                    
import pymysql
import random

def get_random_connection_info():
    # This function generates random connection information for a MySQL database.
    host = f"host{random.randint(1, 100)}"
    user = f"user{random.randint(1, 100)}"
    password = f"pass{random.randint(1, 100)}"
    database = f"db{random.randint(1, 100)}"
    return host, user, password, database

def connect_to_mysql():
    # This function connects to a MySQL database using random connection information.
    host, user, password, database = get_random_connection_info()
    
    try:
        connection = pymysql.connect(host=host,
                                     user=user,
                                     password=password,
                                     database=database)
        print(f"Connected to {database} at {host}")
        return connection
    except pymysql.MySQLError as e:
        print(f"Error connecting to MySQL: {e}")
        return None

def query_database(connection, query):
    # This function executes a query on a MySQL database and returns the results.
    try:
        with connection.cursor() as cursor:
            cursor.execute(query)
            result = cursor.fetchall()
            return result
    except pymysql.MySQLError as e:
        print(f"Error executing query: {e}")
        return None

def close_connection(connection):
    # This function closes the connection to the MySQL database.
    if connection:
        connection.close()
        print("Connection closed")

# Example usage:
if __name__ == "__main__":
    connection = connect_to_mysql()
    if connection:
        query = "SELECT * FROM users"
        result = query_database(connection, query)
        if result:
            print(result)
        close_connection(connection)