3

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)
     ...
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
moeseth
  • 1,855
  • 5
  • 23
  • 47
  • http://flask.pocoo.org/docs/0.10/tutorial/dbcon/ It would create new open connections if you don't close them. You can store the db in a global g instance in flask and then use that to access your database. – sohail288 Dec 12 '15 at 04:02
  • Possible duplicate of [What if I don't close the database connection in Python SQLite](http://stackoverflow.com/questions/9561832/what-if-i-dont-close-the-database-connection-in-python-sqlite). Also check: [When to close cursors using MySQLdb](http://stackoverflow.com/questions/5669878/when-to-close-cursors-using-mysqldb). – Remi Guan Dec 12 '15 at 04:10

2 Answers2

1

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()
masnun
  • 11,635
  • 4
  • 39
  • 50
0

from my experience, close session after use it take significant difference amount of time to response in api whom i've experienced in flask

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

try:
db.session.query( Any Model ...

except:
finally:
db.close_all_sessions
alfianrahmn
  • 9
  • 1
  • 4