Random MySQL Connection and Data Fetching with PyMySQL

  • Share this:

Code introduction


代码含义解释[英文]


Technology Stack : 代码所使用到的包和技术栈[英文]

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import pymysql
import random

def get_random_connection_info():
    host_options = ["localhost", "192.168.1.1", "127.0.0.1", "example.com"]
    user_options = ["root", "admin", "user", "test"]
    password_options = ["password", "123456", "admin", "pass"]
    db_options = ["database1", "db2", "mydb", "testdb"]

    host = random.choice(host_options)
    user = random.choice(user_options)
    password = random.choice(password_options)
    db = random.choice(db_options)

    return host, user, password, db

def create_connection(host, user, password, db):
    try:
        connection = pymysql.connect(host=host, user=user, password=password, db=db)
        print("Connection successful")
        return connection
    except pymysql.MySQLError as e:
        print(f"Error connecting to MySQL: {e}")
        return None

def close_connection(connection):
    if connection:
        connection.close()
        print("Connection closed")

def get_random_data(connection):
    with connection.cursor() as cursor:
        try:
            cursor.execute("SELECT * FROM table_name")
            result = cursor.fetchall()
            return result
        except pymysql.MySQLError as e:
            print(f"Error fetching data from MySQL: {e}")
            return None

def main():
    host, user, password, db = get_random_connection_info()
    connection = create_connection(host, user, password, db)
    data = get_random_data(connection)
    close_connection(connection)
    print(data)

# Code Explanation
"""
This code defines a Python function that uses the PyMySQL library to connect to a MySQL database, fetch random data from a table,
and close the connection. It includes functions to get random connection information, create a connection, close a connection,
and fetch data from the database. The main function orchestrates these steps.
"""

# Technical Stack Explanation
"""
This code uses the PyMySQL library for interacting with MySQL databases in Python. It includes functions to handle database connections,
executing queries, and fetching results. The code demonstrates basic operations such as connecting to a database, executing a SELECT query,
and closing the connection.
"""

# Hardness Level
"""
Intermediate
"""