You can download this code by clicking the button below.
This code is now available for download.
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