› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
androids
V2EX  ›  MySQL

MySQL 数据库连接自动断开的问题

  •  
  •   androids · May 8, 2023 · 3117 views
    This topic created in 1235 days ago, the information mentioned may be changed or developed.

    我用 Fastapi 写了个后端,连接的是 MySQL 数据库,在测试阶段发现,过一晚上再来测试,诸如登录、查询这样的功能,会返回内部错误,但是再多点两下(正好两下)就正常了。

    经过搜索后得知是 MySQL 有一个连接最大空闲时间的参数,默认是 8 小时,刚好一晚上后连接就都断开了。

    我的疑惑是为什么断开连接后要请求三次才能重新建立连接,另外 Fastapi 就不能在用户请求的时候一步到位自动建立连接吗?

    请各位大佬解惑,也给支个招怎么解决。

    7 replies  •  2023-05-10 14:27:53 +08:00
    Oktfolio
        1
    Oktfolio  
       May 8, 2023
    连接池没有没有 keepalive 功能吗?
    stille
        2
    stille  
       May 8, 2023
    正好前些天遇到同样问题。
    加连接池解决了

    ```
    from sqlalchemy.pool import QueuePool

    engine = create_engine(SQLALCHEMY_DATABASE_URL, poolclass=QueuePool,
    pool_size=20, max_overflow=0, pool_recycle=600, pool_pre_ping=True)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

    ```
    cyningxu
        3
    cyningxu  
       May 8, 2023
    这是直接裸连没上连接池吗?
    androids
        4
    androids  
    OP
       May 8, 2023
    @stille 我试试看,谢谢了
    androids
        5
    androids  
    OP
       May 8, 2023
    @cyningxu 不道啊,就对着官方文档一顿咔咔整,文档也没提连接池的事
    androids
        6
    androids  
    OP
       May 8, 2023
    @Oktfolio 有吧,还没整明白
    lyuanxiang20
        7
    lyuanxiang20  
       May 10, 2023 via Android
    有用阿里云的吗?聊聊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   836 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 20:43 · PVG 04:43 · LAX 13:43 · JFK 16:43
    ♥ Do have faith in what you're doing.