Random Table Data Fetcher

  • Share this:

Code introduction


This function randomly selects a table from a MySQL database and retrieves the first 10 rows of that table. It uses the cursor object from the pymysql library to execute SQL queries.


Technology Stack : pymysql, pymysql.cursors, random

Code Type : Database query

Code Difficulty : Intermediate


                
                    
def fetch_random_data(cursor):
    import pymysql.cursors
    import random

    def get_random_table_name():
        table_names = ['users', 'orders', 'products', 'reviews', 'sales']
        return random.choice(table_names)

    def execute_query(query):
        cursor.execute(query)
        result = cursor.fetchall()
        return result

    table_name = get_random_table_name()
    query = f"SELECT * FROM {table_name} LIMIT 10;"
    data = execute_query(query)
    return data