PyMySQL-based MySQL Query Executor

  • Share this:

Code introduction


This function uses the PyMySQL library to connect to a MySQL database, execute a given SQL query, and return the results. It takes a database connection object and an SQL query string as parameters.


Technology Stack : PyMySQL

Code Type : Database operation

Code Difficulty : Intermediate


                
                    
def execute_query(connection, query):
    """
    Execute a given SQL query using PyMySQL connection object and return the result.

    Args:
    connection (pymysql.connect): The connection object to the MySQL database.
    query (str): The SQL query to be executed.

    Returns:
    list: A list of tuples representing the result set returned by the query.
    """
    try:
        with connection.cursor() as cursor:
            cursor.execute(query)
            result = cursor.fetchall()
            return result
    except Exception as e:
        print(f"An error occurred: {e}")
        return None                
              
Tags: