Python は pymysql を使用してデータベースに接続します

 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()

これらのメソッドは、SqlHelperクラス。

  1. execute(sql, *args): SQL ステートメントを実行し、挿入、更新、削除操作をサポートします。SQL ステートメントを最初のパラメーターとしてこのメ​​ソッドに渡すことができ、オプションでパラメーターを ( を使用して*args) SQL ステートメントのパラメーターとして渡すことができます。SQL文を実行してトランザクションをコミットしますが、実行中に例外が発生した場合、トランザクションはロールバックされます。

  2. fetchall(sql, params=None): クエリ ステートメントを実行し、すべての結果を取得します。SQL ステートメントを最初のパラメーターとしてこのメ​​ソッドに渡すことができ、オプションでパラメーターを ( を使用してparams) SQL ステートメントのパラメーターとして渡すことができます。このメソッドはクエリを実行し、結果セット内のすべての行を返します。

  3. fetchone(sql, params=None): クエリ ステートメントを実行し、結果を取得します。SQL ステートメントを最初のパラメーターとしてこのメ​​ソッドに渡すことができ、オプションでパラメーターを ( を使用してparams) SQL ステートメントのパラメーターとして渡すことができます。このメソッドはクエリを実行し、結果セット内のデータ行を返します。

  4. execute_transaction(sql_list): トランザクション操作を実行します。複数の SQL ステートメントを含むリスト ( ) をsql_listパラメータとしてこのメ​​ソッドに渡すことができます。このメソッドは、リスト内の SQL ステートメントを順番に実行し、すべての実行が成功した後にトランザクションをコミットします。SQL ステートメントが失敗すると、トランザクションはロールバックされます。

要約すると次のようになります。

  • execute挿入、更新、および削除操作を実行するために使用される SQL ステートメント。
  • fetchallクエリ ステートメントを実行し、すべての結果を取得するために使用されます。
  • fetchoneクエリステートメントを実行して結果を取得するために使用されます。
  • execute_transaction複数の SQL ステートメントで構成されるトランザクション操作を実行するために使用されます。

テスト:

from mysql_db import db

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

おすすめ

転載: blog.csdn.net/qq_45878280/article/details/131086221
おすすめ