【问题标题】:Over time losing connection to mysql server during queries在查询期间随着时间的推移失去与 mysql 服务器的连接
【发布时间】:2022-01-06 23:01:36
【问题描述】:

我正在使用 MySQL 服务器运行一个不和谐机器人,这两个服务器都在我的 UBUNTU 18.04 服务器上运行。它工作正常,但几个小时后,我每次访问数据库时都会出现错误。

Traceback (most recent call last):
  File "/home/narnar/.local/lib/python3.7/site-packages/discord_slash/client.py", line 1352, in invoke_command
    await func.invoke(ctx, **args)
  File "/home/narnar/.local/lib/python3.7/site-packages/discord_slash/model.py", line 209, in invoke
    return await self.func(self.cog, *args, **kwargs)
  File "/home/narnar/cool-art/cogs/artlevels.py", line 120, in leaderboardCommand
    cur.execute("SELECT * FROM artLevels")
  File "/home/narnar/.local/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 271, in execute
    raw_as_string=self._raw_as_string)
  File "/home/narnar/.local/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 522, in cmd_query
    sqlstate=exc.sqlstate)
mysql.connector.errors.OperationalError: 2013 (HY000): Lost connection to MySQL server during query

【问题讨论】:

  • 服务器的wait_timeout是否超出?默认为 8 小时。可能可以捕获此异常并重新连接。
  • 重新连接什么?
  • MySQL 服务器。

标签: mysql mysql-python


【解决方案1】:

我通过长时间不打开连接解决了这个问题。我的程序在程序开始时连接到 MySQL 服务器,并一直使用相同的连接。因此,我没有建立一个连接,而是在需要访问数据库时打开一个连接,然后将其关闭。只要确保您的连接没有打开太久

不要这样做:

con = mysql.connector.connect(
        host=host,
        user="ImNotThat",
        passwd="Stupid",
        database="toShowMyPasswords"
 )


async def someListenerEvent():
     doThing()
     con.commit()

这样做:

async def someListenerEvent():
    con = mysql.connector.connect(
        host=host,
        user="ImNotThat",
        passwd="Stupid",
        database="toShowMyPasswords"
    )
    doThing()
    con.commit()
    cur.close()
    con.close()
    

【讨论】:

    猜你喜欢
    • 2010-12-25
    • 2011-03-28
    • 2012-11-15
    • 2015-09-22
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多