python - 是否需要在 Flask 应用程序中关闭 python SQL 连接?

标签 python mysql flask

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

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

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

最佳答案

最好关闭连接。您可以将代码放在 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()

关于python - 是否需要在 Flask 应用程序中关闭 python SQL 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34235997/

相关文章:

c++ - 我应该在 C++ 之后学习 Python 吗?

php - PEAR HTML_Quick Form函数和处理数据

访问 Flask 请求参数的 Pythonic 方式

Python:在二维数组中查找所有可能的唯一双索引组合

python - 无法使用python客户端连接到go grpc服务器

php - 跨域的所有页面都需要 HTTPS

mysql - mysql中的alter语句失败

python - 类型错误 : list object is not an iterator

python - 工作人员完成后重定向用户

Python 时间序列预测(销量)