Random Record Fetcher from MySQL Database

  • Share this:

Code introduction


This function connects to a MySQL database, randomly selects a table, and then randomly selects a record from the table and returns it.


Technology Stack : pymysql

Code Type : Database operation

Code Difficulty : Intermediate


                
                    
def fetch_random_record(cursor):
    import random
    from pymysql import connect, Error

    try:
        # Connect to the MySQL database
        connection = connect(host='localhost',
                             user='your_username',
                             password='your_password',
                             database='your_database')
        
        # Select a random table from the database
        cursor.execute("SHOW TABLES")
        tables = cursor.fetchall()
        random_table = tables[random.randint(0, len(tables) - 1)][0]

        # Select a random record from the selected table
        cursor.execute(f"SELECT * FROM {random_table} LIMIT 1")
        random_record = cursor.fetchone()
        
        # Return the random record
        return random_record

    except Error as e:
        print(f"Error: {e}")

    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()                
              
Tags: