aiomysql数据库连接池不能正确读取数据?

问题描述

用数据库连接池查询数据的时候,如果手动更改数据库数据,再次查询时的数据为之前的未更改的数据

问题出现的环境背景及自己尝试过哪些方法

python3.7
aiomyqsl 0.0.20

相关代码

class Test(object):
    async def _pool(self):
        self.pool = await aiomysql.create_pool(**mysql_options)

    async def get_one(self, sql, param=None):
        await self.cur.execute(sql, param)
        result = await self.cur.fetchone()
        return result

    async def get(self):
        self.conn = await self.pool.acquire()
        self.cur = await self.conn.cursor(DictCursor)
        sql = '''select policy from tb_user where id = 2;'''
        res = await self.get_one(sql)
        print(res)
        await self.cur.close()
        await self.pool.release(self.conn)

    @staticmethod
    def update():
        import pymysql
        coon = pymysql.connect(host='127.0.0.1',
                               port=3306,
                               user=mysql_options['user'],
                               autocommit=True,
                               password=mysql_options['password'],
                               database=mysql_options['db'])
        cursor = coon.cursor()
        sql = '''update tb_user set policy = 9 where id = 2;'''
        cursor.execute(sql)
        sql = '''select policy from tb_user where id = 2;'''
        cursor.execute(sql)
        data = cursor.fetchone()
        print(data)
    async def run(self):
        await self._pool()
        await self.get()
        self.update()
        await self.get()


if __name__ == '__main__':
    test = Test()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(test.run())

你期待的结果是什么?实际看到的错误信息又是什么?

执行结果
image.png

阅读 1.9k
1 个回答
新手上路,请多包涵

自己也遇到了这个问题,试了一下午找到原因了,回答一下希望能帮到遇到同样问题的人。
这个问题的原因是 aiomysql 连接池如果 autocommit 为 False,则需要手动设置事务隔离级别,在创建连接时,使用 init_command 参数自动执行设置隔离级别的 SQL 命令

import aiomysql

async def get_connection():
    conn = await aiomysql.connect(
        host='localhost',
        user='user',
        password='password',
        db='mydb',
        autocommit=False,
        init_command="SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED"
    )
    return conn

设置之后执行查询命令时,可以读取别的事务已经提交的 commit,保证了数据的实时性准确性

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题