首页 > 解决方案 > 在哪里放置 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 以关闭所有数据库连接

标签: python

解决方案


考虑在这里使用上下文管理器:

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值得一读的标准。


推荐阅读