python - 在哪里放置 db.close 以关闭 python 脚本中函数内部的 mysql 连接
问题描述
我有这个伪代码,我想在 for 循环之后关闭 mysql 连接
但我收到以下错误:
Traceback (most recent call last):
File "./myscript.py", line 201, in <module>
db.close
NameError: name 'db' is not defined
代码如下所示:
def get_content(id):
db = mysql.connector.connect(host='localhost',user='user',password='password',database='dcname')
#get cursor
cursor = db.cursor()
cursor.execute("select id,num from table where job_db_inx={0}".format(index))
result = cursor.fetchall()
for job in list
id = get_content(id)
print(id)
db.close()
我应该在哪里放置 db.close 以关闭所有数据库连接
解决方案
考虑在这里使用上下文管理器:
import contextlib
def get_content(id, cursor):
cursor.execute("select id,num from table where job_db_inx={0}".format(index))
result = cursor.fetchall()
with contextlib.closing(mysql.connector.connect(...)) as conn:
cursor = conn.cursor()
for job in list
id = get_content(id, cursor)
print(id)
我contextlib.closing
在这里使用过,但很有可能任何给定的 db api 都已经实现为它自己的上下文管理器。Python 有一个dbapi
值得一读的标准。
推荐阅读
- java - 如何在 Java 中向我的 OpenAPI 类添加多级扩展?
- javascript - 如何在js上搜索多个参数
- stripe-payments - 条带密钥安全?
- java - Springboot:注入bean时ScriptUtils不会在H2中播种数据
- javascript - 如何使用 Vue 路由器将数据传递给另一个组件?
- for-loop - 仅循环的批处理文件计数为 8
- python - 使用 Json Python 格式化 Websocket 数据
- java - 用于两个类似命名元素的 JAXB XJB
- python - 来自预训练张量流模型的混淆矩阵
- doxygen - Doxygen 没有提取所有文件