在哪里放置db.close以关闭python脚本中函数内部的mysql连接



我有这个psudo代码,我想在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,但很有可能任何给定的dbapi都已经实现为自己的上下文管理器。Python有一个值得一读的标准dbapi

实际代码应该如下所示:(确保conn已关闭(

def get_content(id,conn):
cursor = conn.cursor()
cursor.execute("select  id,num from table  where job_db_inx={0}".format(id))
result = cursor.fetchall()
return result
try:
conn = mysql.connector.connect(host='localhost',user='user',password='password',database='dcname')
for job in list
id = get_content(id,conn)
print(id)
finally:
conn.close()

最新更新