简体   繁体   English

何时关闭 MySQL 连接 discord.py

[英]When to close MySQL connection discord.py

I want to make a discord bot that saves data to a MySQL Database (currently localhost) but the problem is I don't know when to close the database connection.我想制作一个将数据保存到 MySQL 数据库(当前为 localhost)的不和谐机器人,但问题是我不知道何时关闭数据库连接。 Currently, when the user enters the command it always creates a new connection to the database but as you can imagine it's very slow to always connect then execute the query then close the connection, and finally after then returning the data.目前,当用户输入命令时,它总是会创建一个到数据库的新连接,但是你可以想象,总是连接然后执行查询然后关闭连接,最后返回数据是非常慢的。

Here is an example:下面是一个例子:

 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()

But I'm afraid if I connect to the DB at the beginning the bot crashers or so and then I've never closed the connection to the database.但是我担心如果我在开始时连接到数据库,机器人崩溃左右然后我从未关闭到数据库的连接。 Is there a way to make it better?有没有办法让它更好?

every connection has an idle timeout, that would detect a unused open connection and close it.每个连接都有一个空闲超时,它会检测一个未使用的打开连接并关闭它。

But your approach is very good and clean, as it closes the connection但是您的方法非常好且干净,因为它关闭了连接

A much simpler approach is to add finqally as all try catch and ecept will run through it一个更简单的方法是添加finqally因为所有 try catch 和 ecept 都会通过它

Also use prepared statements, when using variabels使用变量时也使用准备好的语句

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM