【问题标题】:Is it required to close python SQL connection in Flask app?是否需要在 Flask 应用程序中关闭 python SQL 连接?
【发布时间】:2016-03-18 02:26:33
【问题描述】:

我有下面这样的代码。是否有必要关闭mysql连接,因为每当我的主页被请求时,都会创建一个新的sql连接?

我随机收到连接限制错误。但我不确定是不是数据库连接的问题。

@app.route("Home", methods=["GET"])
def get_home_page():
     db = mysql.connect(host, user, password, db_name, charset='utf8', use_unicode=True)
     ...

【问题讨论】:

标签: python mysql flask


【解决方案1】:

关闭连接是个好习惯。您可以将代码放入 try..finally 块中。

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

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 2011-04-02
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    相关资源
    最近更新 更多