Selecting Random Column and Row from MySQL Table

  • Share this:

Code introduction


The code defines a function to select a random column and its corresponding random row from a specified MySQL database table.


Technology Stack : The code uses the PyMySQL library to connect to a MySQL database, retrieve column names from the INFORMATION_SCHEMA, and select a random column and row from the specified table.

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def select_random_column_from_table(db, table_name):
    import pymysql
    import random

    # Connect to the MySQL database
    connection = pymysql.connect(host='localhost',
                                 user='yourusername',
                                 password='yourpassword',
                                 database='yourdatabase',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            # Select a random column name from the database table
            cursor.execute(f"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table_name}'")
            columns = cursor.fetchall()
            if not columns:
                raise ValueError(f"No columns found in table '{table_name}'")
            random_column = random.choice(columns)[0]

            # Select a random row from the table using the randomly selected column
            cursor.execute(f"SELECT {random_column} FROM {table_name}")
            random_row = cursor.fetchone()
            return random_row
    finally:
        connection.close()