Question: i have this psudo code which i want to close the mysql connection after the for loop

but i am getting the below error:

```
    Traceback (most recent call last):
    File "./myscript.py", line 201, in <module>
    db.close
    NameError: name 'db' is not defined

```

the code looks like the below:

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

```

where should i place the db.close to close all the db connections

Answer: 
Consider using a context manager here:

```
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)

```

I used [`contextlib.closing`](https://docs.python.org/3/library/contextlib.html#contextlib.closing) here, but there's a very good chance that any given db api is already implemented as its own context manager. Python has a standard [`dbapi`](https://www.python.org/dev/peps/pep-0249) that is worth reading.
The actual code should look like: (make sure `conn` is closed)

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

```