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