aiomysql单例模式

本文介绍了一个使用Python的`aiomysql`库实现的数据库连接类`DatabaseSingleton`,通过SingletonType元类和RLock确保了连接的线程安全。方法包括连接、执行查询、更新和关闭连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from threading import RLock

import aiomysql


class SingletonType(type):
    single_lock = RLock()

    def __call__(cls, *args, **kwargs):  # 创建cls的对象时候调用
        with SingletonType.single_lock:
            if not hasattr(cls, "_instance"):
                cls._instance = super(SingletonType, cls).__call__(*args, **kwargs)  # 创建cls的对象

        return cls._instance


class DatabaseSingleton(metaclass=SingletonType):
    def __init__(self):
        self.pool = None

    DB_CONFIG = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'password': '123456',
        'db': 'test_db',
    }

    async def connect(self):
        self.pool = await aiomysql.create_pool(
            **self.DB_CONFIG
        )

    async def execute_query(self, query):
        async with self.pool.acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute(query)
                result = await cur.fetchall()
                return result

    async def execute_query_with_columns(self, query):
        """
        使用 select * 时使用,返回查询结果数量和数据
        :param query:
        :return:
        """
        async with self.pool.acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute(query)
                result = await cur.fetchall()
                column_names = [desc[0] for desc in cur.description]
                length = len(result)
                data = []
                if length == 0:
                    return length, data
                for row in result:
                    t = {}
                    for col_name, col_value in zip(column_names, row):
                        t[col_name] = col_value
                    data.append(t)
                return length, data

    async def update(self, query):
        async with self.pool.acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute(query)
                await cur.connection.commit()
                return "OK"

    async def close(self):
        if self.pool is not None:
            self.pool.close()
            await self.pool.wait_closed()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值