Random Record Fetch from MySQL Database with PyMySQL

  • Share this:

Code introduction


This function fetches a random record from a MySQL database using PyMySQL. It first executes a SQL query using the cursor object from the PyMySQL library, which randomly selects a record from a specified table. Then, it fetches the result using the fetchone() method.


Technology Stack : PyMySQL, MySQL database

Code Type : Database Function

Code Difficulty : Intermediate


                
                    
import pymysql
import random

def fetch_random_record(cursor):
    """
    Fetches a random record from a MySQL database using PyMySQL.
    """
    try:
        cursor.execute("SELECT * FROM table_name LIMIT 1 OFFSET %s", (random.randint(0, 100),))
        record = cursor.fetchone()
        return record
    except pymysql.MySQLError as e:
        print(f"Error: {e}")
        return None