Random Record Fetcher from #random_table#

  • Share this:

Code introduction


This function fetches a random record from a database table named 'random_table'. It first executes a SELECT query and then randomly selects and returns a record from the query results.


Technology Stack : psycopg2

Code Type : Database operation

Code Difficulty : Intermediate


                
                    
import psycopg2
import random

def fetch_random_record(cursor):
    """
    Fetches a random record from the database using psycopg2.

    Args:
    cursor (psycopg2.cursor): A cursor object used to interact with the database.

    Returns:
    dict: A dictionary containing the fetched record.
    """
    cursor.execute("SELECT * FROM random_table;")  # Assuming there is a table named 'random_table'
    rows = cursor.fetchall()
    random_index = random.randint(0, len(rows) - 1)
    return rows[random_index]

# Usage example:
# conn = psycopg2.connect(
#     dbname="your_dbname",
#     user="your_username",
#     password="your_password",
#     host="your_host"
# )
# cursor = conn.cursor()
# result = fetch_random_record(cursor)
# print(result)
# cursor.close()
# conn.close()                
              
Tags: