MySQL Database Interaction Functions

  • Share this:

Code introduction


This code block defines a function that connects to a MySQL database, executes a query, fetches a single record, and closes the database connection.


Technology Stack : pymysql

Code Type : Database operation function

Code Difficulty : Intermediate


                
                    
import pymysql
import random

def connect_database(host, user, password, db):
    """
    Connect to a MySQL database using pymysql.
    """
    connection = pymysql.connect(host=host, user=user, password=password, db=db)
    return connection

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

def fetch_single_record(connection, query):
    """
    Fetch a single record from the database using pymysql.
    """
    with connection.cursor() as cursor:
        cursor.execute(query)
        record = cursor.fetchone()
    return record

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

# JSON explanation                
              
Tags: