Python uses pymysql to connect to the database

 mysql_db.py

import pymysql
from dbutils.pooled_db import PooledDB
import logging

class SqlHelper(object):
    def __init__(self):
        self.pool = PooledDB(
            creator=pymysql,  
            maxconnections=5,  
            mincached=2,  
            blocking=True,  
            ping=0,
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123456',
            database='test',
            charset='utf8'
        )

        self.logger = logging.getLogger("SqlHelper")
        self.logger.setLevel(logging.DEBUG)

        # 创建文件日志处理器
        file_handler = logging.FileHandler("sqlhelper.log")
        file_handler.setLevel(logging.DEBUG)

        # 设置日志格式
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        file_handler.setFormatter(formatter)

        # 将日志处理器添加到日志记录器
        self.logger.addHandler(file_handler)

    def open(self):
        """打开数据库连接"""
        conn = self.pool.connection()
        cursor = conn.cursor()
        return conn, cursor

    def close(self, cursor, conn):
        """关闭数据库连接"""
        cursor.close()
        conn.close()

    def execute(self, sql, *args):
        """执行SQL语句,支持插入、更新和删除操作"""
        conn, cursor = self.open()
        try:
            cursor.execute(sql, args)
            conn.commit()
        except Exception as e:
            conn.rollback()
            self.logger.error(f"Error executing SQL: {sql}\nError message: {str(e)}")
        finally:
            self.close(cursor, conn)

    def fetchall(self, sql, params=None):
        """获取所有数据"""
        conn, cursor = self.open()
        try:
            cursor.execute(sql, params)
            result = cursor.fetchall()
            return result
        except Exception as e:
            self.logger.error(f"Error executing SQL: {sql}\nError message: {str(e)}")
        finally:
            self.close(cursor, conn)

    def fetchone(self, sql, params=None):
        """获取一条数据"""
        conn, cursor = self.open()
        try:
            cursor.execute(sql, params)
            result = cursor.fetchone()
            return result
        except Exception as e:
            self.logger.error(f"Error executing SQL: {sql}\nError message: {str(e)}")
        finally:
            self.close(cursor, conn)

    def execute_transaction(self, sql_list):
        """执行事务"""
        conn, cursor = self.open()
        try:
            for sql in sql_list:
                cursor.execute(sql)
            conn.commit()
        except Exception as e:
            conn.rollback()
            self.logger.error(f"Error executing transaction: {str(e)}")
        finally:
            self.close(cursor, conn)

# 创建 SqlHelper 实例
db = SqlHelper()

These methods have different purposes and behaviors when using SqlHelperthe class :

  1. execute(sql, *args): Execute SQL statements, support insert, update and delete operations. You can pass an SQL statement as the first parameter to this method, and optionally pass parameters (using *args) as parameters for the SQL statement. This method executes the SQL statement and commits the transaction. If an exception occurs during execution, the transaction will be rolled back.

  2. fetchall(sql, params=None): Execute the query statement and get all the results. You can pass an SQL statement as the first parameter to this method, and optionally pass parameters (using params) as parameters for the SQL statement. This method executes the query and returns all the rows in the result set.

  3. fetchone(sql, params=None): Execute the query statement and get a result. You can pass an SQL statement as the first parameter to this method, and optionally pass parameters (using params) as parameters for the SQL statement. This method executes the query and returns a row of data in the result set.

  4. execute_transaction(sql_list): Executes a transaction operation. You can pass a list ( ) containing multiple SQL statements sql_listas parameters to this method. This method executes the SQL statements in the list sequentially, and commits the transaction after all executions are successful. If any SQL statement fails, the transaction will be rolled back.

To sum it up:

  • executeSQL statements used to perform insert, update, and delete operations.
  • fetchallUsed to execute query statements and get all results.
  • fetchoneIt is used to execute a query statement and obtain a result.
  • execute_transactionUsed to execute transaction operations consisting of multiple SQL statements.

test:

from mysql_db import db

res = db.fetchall("select * from user")
print(res)

Guess you like

Origin blog.csdn.net/qq_45878280/article/details/131086221