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()
aiomysql单例模式
最新推荐文章于 2024-11-03 00:03:15 发布