Random Query Database Execution

  • Share this:

Code introduction


This function accepts database connection information and a SQL query string as arguments, connects to the database, executes the query, and finally returns the first row of the query result.


Technology Stack : PyMySQL, pymysql, random, DictCursor

Code Type : Database query function

Code Difficulty : Intermediate


                
                    
def random_query_database(host, user, password, database, query):
    import pymysql
    import random
    from pymysql.cursors import DictCursor
    
    # Connect to the database
    connection = pymysql.connect(host=host,
                                 user=user,
                                 password=password,
                                 database=database,
                                 cursorclass=DictCursor)
    
    try:
        # Execute the random query
        with connection.cursor() as cursor:
            cursor.execute(query)
            # Fetch the result
            result = cursor.fetchone()
            return result
    finally:
        # Close the connection
        connection.close()