flask 》》pymysql VS FastAPI aiomysql

pymysql 同步 flask使用

python 复制代码
import pymysql

# 同步连接,会阻塞当前线程
connection = pymysql.connect(
    host='localhost',
    user='root',
    password='123456',
    database='test'
)

try:
    with connection.cursor() as cursor:
        # 同步执行,等待期间线程被阻塞
        cursor.execute("SELECT * FROM users WHERE id = %s", (1,))
        result = cursor.fetchone()
        print(result)
        
        # 事务操作
        connection.begin()
        cursor.execute("UPDATE users SET name = %s WHERE id = %s", ("newname", 1))
        connection.commit()
finally:
    connection.close()

aiomysql 异步 fastAPI使用

python 复制代码
import asyncio
import aiomysql

async def main():
    # 异步连接,不会阻塞事件循环
    pool = await aiomysql.create_pool(
        host='localhost',
        user='root',
        password='123456',
        db='test',
        minsize=5,
        maxsize=20
    )
    # acquire 获得 
    async with pool.acquire() as conn:
        async with conn.cursor() as cursor:
            # 异步执行,等待期间让出控制权
            await cursor.execute("SELECT * FROM users WHERE id = %s", (1,))
            result = await cursor.fetchone()
            print(result)
            
            # 事务操作
            await conn.begin()
            await cursor.execute("UPDATE users SET name = %s WHERE id = %s", ("newname", 1))
            await conn.commit()
    
    pool.close()
    await pool.wait_closed()

# 运行异步函数
asyncio.run(main())
相关推荐
weixin_3823952311 分钟前
本地部署 ERP 选型记录:从 Excel 到轻量系统的这几年
数据库·人工智能·数据挖掘
2401_8914092638 分钟前
期货量化用得上的几类行情数据:逐笔、Level2、分钟线和五档tick
数据库
海绵宝宝转agent1 小时前
基于Redis ZSet+AOP+注解实现限流注解算法
数据库·redis·算法
imDwAaY2 小时前
Redis 也能做消息队列?从 Stream 的存储讲到消费确认
数据库·redis·缓存
@Mike@2 小时前
13-数据库学习笔记(查询执行处理模型)
数据库·笔记·学习
弈栈录2 小时前
MySQL 事务、索引与锁:后端开发必须掌握的数据库基础
数据库·后端
9624562 小时前
餐饮 SaaS 优惠券系统架构演进(三):优惠计算引擎——商品级计价、冲突策略与优惠分摊
java·数据库·spring boot
染指11102 小时前
135.Agent-多Agent框架-LangChain多智能体(SubAgents子代理)
数据库·人工智能·设计模式·langchain·agent·agents
Elastic 中国社区官方博客3 小时前
错误最多的服务运行正常:使用 ES|QL 从日志进行根因分析
大数据·运维·数据库·sql·elasticsearch·搜索引擎·全文检索
做运维的阿瑞3 小时前
mysql数据库视图笔记:创建、修改、删除与适用场景
数据库·笔记·mysql