You can download this code by clicking the button below.
This code is now available for download.
This function connects to a database, executes a random query, and returns one random record from the query results.
Technology Stack : PyMySQL
Code Type : Database query
Code Difficulty : Intermediate
def fetch_random_record(db, query):
import pymysql.cursors
import random
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='password',
database='mydb',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Execute the query
cursor.execute(query)
# Fetch a random record
cursor.execute("SELECT * FROM(SELECT * FROM table_name ORDER BY RAND() LIMIT 1);")
record = cursor.fetchone()
return record
finally:
connection.close()