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())
相关推荐
Escalating_xu18 小时前
【MySQL】事务管理(上):从 ACID 到提交回滚,把一次转账真正做完整
android·数据库·mysql
不喝水就会渴20 小时前
「不想上班」实战系列:密码卡证保险箱 —— 主密钥存入 Asset,密文落库 RDB【鸿蒙心迹】
数据库·oracle
西泽XIZ920 小时前
微信小程序网络与数据库交互实践:从后端环境搭建到数据渲染
网络·数据库·微信小程序·小程序
TiDB 社区干货传送门1 天前
平凯数据库携手东软医保共筑智慧医保,构建可靠、安全、开放的数据底座
数据库·tidb·国产数据库
YYYing.1 天前
【Mysql剑指offer系列 (七) 】MySQL性能调优和架构
数据库·mysql·八股
Decay__1 天前
PostgreSQL WAL 归档与时间点恢复 —— WAL 连续归档、recovery_target 时点恢复与 pg_rewind
运维·数据库·sql·postgresql
如夏倾城1 天前
大模型(Large Model)解析:从数据类型、模型架构到任务选型
服务器·网络·数据库·语言模型·架构·audiolm
船神丿男人1 天前
Redis 缓存击穿与雪崩实测:同键合并、TTL 错峰与迟到回填
数据库·redis·缓存
富贵儿9981 天前
NL2SQL 实践手记 04:多表查询为什么更难——让模型找对表、连对关系
数据库·sql·ai·自然语言处理·langchain