【问题标题】:When to close MySQL connection discord.py何时关闭 MySQL 连接 discord.py
【发布时间】:2021-09-26 03:20:56
【问题描述】:

我想制作一个不和谐的机器人,将数据保存到 MySQL 数据库(当前为 localhost),但问题是我不知道何时关闭数据库连接。 目前,当用户输入命令时,它总是会创建一个与数据库的新连接,但正如您可以想象的那样,总是连接然后执行查询然后关闭连接,最后再返回数据之后会很慢。

这是一个例子:

def open_case(case_id):
        search_query = f"SELECT `CASE_ID`, `USER_ID`, `LINK_REASON`, `LINK_SCREENSHOT` FROM `Report` WHERE CASE_ID ='{case_id}'"`

        mydb = mysql.connector.connect(
            host = "localhost",
            database = "report",
            password = "root",
            username = "root"
        )

        cursor = mydb.cursor()
        try:
            cursor.execute(search_query)
            result = cursor.fetchall()
            mydb.close()

        return result
    except:
        return print("Error case not found")
        mydb.close()

但我担心如果我一开始就连接到数据库,机器人崩溃者左右,然后我就从来没有关闭到数据库的连接。 有没有办法让它变得更好?

【问题讨论】:

    标签: python mysql discord.py


    【解决方案1】:

    每个连接都有一个空闲超时,它会检测到未使用的打开连接并关闭它。

    但是你的方法非常好,干净,因为它关闭了连接

    一个更简单的方法是添加finqally,因为所有的try catch 和ecept 都会运行它

    在使用变量时也要使用准备好的语句

    def open_case(case_id):
            search_query = "SELECT `CASE_ID`, `USER_ID`, `LINK_REASON`, `LINK_SCREENSHOT` FROM `Report` WHERE CASE_ID =%s"
    
            mydb = mysql.connector.connect(
                host = "localhost",
                database = "report",
                password = "root",
                username = "root"
            )
    
            cursor = mydb.cursor()
            try:
                cursor.execute(search_query,(case_id,))
                result = cursor.fetchall()
                return result      
            except:
                result = print("Error case not found")
            finally:
                mydb.close()
    open_case(1)
    

    【讨论】:

    • 谢谢,但正如我所提到的,它非常缓慢。或者如果我不关闭它就崩溃了会有很大的问题
    • 在我更改的答案中写了一个更好的方法,这也保证不会发生 sql 注入
    • 谢谢,但是为什么 cursor.execute(search_query,(case_id,)) 中的 case_id 后面有一个 ,
    • 那是一个prepared statement,所以不能进行sql注入。请不要忘记upvote and accept the answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2016-04-04
    • 1970-01-01
    • 2021-12-01
    • 2011-05-08
    • 2014-12-18
    • 2012-11-03
    相关资源
    最近更新 更多