PyMySQL Database Operations: Connect, Query, and Close

  • Share this:

Code introduction


This function defines three functionalities: connecting to a MySQL database, executing a query and returning the result, and closing the database connection. These operations are performed using the PyMySQL library.


Technology Stack : PyMySQL

Code Type : Function

Code Difficulty : Intermediate


                
                    
import pymysql
import random

def connect_to_database(host, user, password, database):
    """
    Connect to a MySQL database using PyMySQL and return the connection object.
    """
    connection = pymysql.connect(host=host, user=user, password=password, database=database)
    return connection

def execute_query(connection, query):
    """
    Execute a query on a MySQL database using PyMySQL and return the result.
    """
    with connection.cursor() as cursor:
        cursor.execute(query)
        result = cursor.fetchall()
    return result

def close_connection(connection):
    """
    Close the connection to a MySQL database.
    """
    connection.close()

# JSON Explanation                
              
Tags: