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())
相关推荐
牧瀬クリスだ4 分钟前
关于MySql安装与可视化工具推荐
数据库·mysql
InfinteJustice5 分钟前
Go语言如何用AWS Lambda_Go语言AWS Lambda教程【对比】
jvm·数据库·python
一只大袋鼠11 分钟前
JDBC 详细笔记:从基础 API 到 SQL 注入解决
数据库·笔记·sql·mysql
InfinteJustice14 分钟前
MySQL如何实现数据库审计日志记录_开启通用日志与插件审计
jvm·数据库·python
Shorasul14 分钟前
mysql如何利用并行查询提速_mysql 8.0并行扫描特性.txt
jvm·数据库·python
m0_7164300718 分钟前
如何截断SQL小数位数_使用TRUNCATE函数控制精度
jvm·数据库·python
2301_7826591819 分钟前
mysql如何进行全量数据库备份_mysqldump工具的使用技巧
jvm·数据库·python
王仲肖28 分钟前
PostgreSQL 统计信息 — 完整总结与优化指南
数据库·postgresql
有想法的py工程师30 分钟前
PostgreSQL vs PolarDB:Checkpoint 调优策略深度对比(高频 vs 低频)
大数据·数据库·postgresql
m0_3776182332 分钟前
golang如何使用struct嵌套_golang struct结构体嵌套使用方法.txt
jvm·数据库·python