Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it required to close python SQL connection in Flask app?

I've the code like this below. Is it necessary to close mysql connection because whenever my home page is requested, a new sql connection will be created?

I randomly get Connection Limit error. But I'm not sure if the DB connection is the problem.

@app.route("Home", methods=["GET"])
def get_home_page():
     db = mysql.connect(host, user, password, db_name, charset='utf8', use_unicode=True)
     ...
like image 893
moeseth Avatar asked Sep 26 '26 02:09

moeseth


1 Answers

It is good practice to close the connection. You can put your codes inside a try..finally block.

@app.route("Home", methods=["GET"])
def get_home_page():
     db = mysql.connect(host, user, password, db_name, charset='utf8', use_unicode=True)
     try:
       ... do something ...
     finally:
         db.close()
like image 96
masnun Avatar answered Sep 28 '26 17:09

masnun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!