Random Data Selection from MySQL Database

  • Share this:

Code introduction


This function connects to a specified MySQL server, randomly selects a database, a table, and a column, and then randomly selects a row of data to return.


Technology Stack : PyMySQL, pymysql, random

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_select_connection_info(host, user):
    import pymysql
    import random
    
    connection = pymysql.connect(host=host, user=user, cursorclass=pymysql.cursors.DictCursor)
    
    # Randomly select a database from the list of databases available in the MySQL server
    databases = connection.cursor().execute("SHOW DATABASES;").fetchall()
    database = random.choice([db['Database'] for db in databases])
    
    # Randomly select a table from the list of tables available in the selected database
    tables = connection.cursor().execute(f"SHOW TABLES IN {database};").fetchall()
    table = random.choice([table['Tables_in_' + database] for table in tables])
    
    # Randomly select a column from the list of columns available in the selected table
    columns = connection.cursor().execute(f"SHOW COLUMNS FROM `{table}`;").fetchall()
    column = random.choice([col['Field'] for col in columns])
    
    # Randomly select a row from the selected table
    row = connection.cursor().execute(f"SELECT * FROM `{table}` LIMIT 1;").fetchone()
    
    return row