Random Row Selection from Database Table

  • Share this:

Code introduction


This function connects to a specified database and randomly selects a row from the specified table to return. It uses the connection, query, and result retrieval functions of the PyMySQL library.


Technology Stack : PyMySQL, pymysql.cursors, random

Code Type : Database Query

Code Difficulty : Intermediate


                
                    
def random_select_from_pymysql(db, table):
    import pymysql.cursors
    import random

    # Connect to the database
    connection = pymysql.connect(host='localhost',
                                 user='user',
                                 password='password',
                                 db='database',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            # Select a random row from the table
            sql = "SELECT * FROM %s ORDER BY RAND() LIMIT 1" % table
            cursor.execute(sql)
            result = cursor.fetchone()
        return result
    finally:
        connection.close()