aiomysql踩坑日志

aiomysql脏读的解决办法

创建连接池时增加 autocommit=True

#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Author         : Charlie Zhang
# @Email          : [email protected]
# @Time           : 2021/1/25 17:22
# @Version        : 1.0
# @File           : test.py
# @Software       : PyCharm

import aiomysql
from aiomysql import Pool, OperationalError

from core import config


async def get_wise_pool(min_s: int, max_s: int) -> Pool:
    try:
        pool = await aiomysql.create_pool(
            host=config.MYSQL_HOST,
            port=config.MYSQL_PORT,
            user=config.MYSQL_USER,
            password=config.MYSQL_PWD,
            db=config.MYSQL_DB,
            autocommit=True,  # 此处增加 autocommit=True
            minsize=min_s,
            maxsize=max_s,
        )
        return pool
    except OperationalError as e:
        print(f"Failed connected to mysql '{config.MYSQL_HOST}', errmsg: {e}")

aiomysql连接池无法连接到MySQL

在执行增删改查操作前await conn.ping()

#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Author         : Charlie Zhang
# @Email          : [email protected]
# @Time           : 2021/1/25 17:22
# @Version        : 1.0
# @File           : test.py
# @Software       : PyCharm

from aiomysql import Pool, OperationalError


async def curd_tool(pool, sql, params=None, multiple=True):
    """
    aiomysql操作中心
    :param pool: 连接池
    :param sql:
    :param params:
    :param multiple: 是否查询多个
    :return:
    """
    try:
        async with pool.acquire() as conn:
            await conn.ping() # 此处增加ping
            async with conn.cursor() as cur:
                await cur.execute(sql, params)
                if str(sql).split(' ')[0].lower() in ('insert', 'update', 'delete'):
                    await conn.commit()
                    return
                return await cur.fetchall() if multiple else await cur.fetchone()
    except OperationalError as e:
        print(f'aiomysql error: {e}')
        return []