mysql.py 1.62 KB
Newer Older
崔为之's avatar
崔为之 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/11/12 11:08
# @File        : mysql.py
# @Description :
"""

from typing import Optional

import pymysql
from dbutils.pooled_db import PooledDB


class MySQLHelper:

    def __init__(self, **kwargs):
        """
        Initialize the MySQLHelper class, create a database connection pool
        """
        self.kwargs = kwargs if kwargs else {}
        self.conn = None
        self.db_pool = PooledDB(pymysql, **self.kwargs)

    def __enter__(self):
        """
        Implement the __enter__ magic method, support the with statement
        """
        self.conn = self.db_pool.connection()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Implement the __exit__ magic method, support the with statement
        """
        if self.conn:
            self.conn.close()
        if exc_type:
            print(f"Error occurred: {exc_val}")

    def execute(self, sql: str) -> Optional[tuple]:
        """
        Execute the SQL statement and retrieve the results
        """
        if not self.conn:
            print("No connection available.")
            return None

        try:
            # Use the cursor object to execute SQL statement
            with self.conn.cursor() as cursor:
                cursor.execute(sql)
                result = cursor.fetchall()
                return result

        except Exception as e:
            print(f"Error executing SQL: {e}")
            return None