随着时间的推移,在查询期间失去与 mysql 服务器的连接

Over time losing connection to mysql server during queries

我是 运行 一个使用 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

我通过长时间不打开连接解决了这个问题。我的程序在程序开始时连接到 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()