简体   繁体   中英

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. 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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