Question: I am doing something like this...

```
conn = sqlite3.connect(db_filename)

with conn:
    cur = conn.cursor()
    cur.execute( ... )

```

`with` automatically commits the changes. But the docs say nothing about closing the connection. 

Actually I can use `conn` in later statements (which I have tested). Hence it seems that the context manager is not closing the connection.

Do I have to manually close the connection. What if I leave it open?

**EDIT**

My findings:

* The **connection is not closed** in the context manager, I have tested and confirmed it. Upon `__exit__`, the context manager only commits the changes by doing `conn.commit()`
* `with conn` and `with sqlite3.connect(db_filename) as conn` are same, so using either will still keep the connection alive
* `with` statement does not create a new scope, hence all the variables created inside the suite of with will be accessible outside it
* Finally, you should close the connection manually

Answer: 
This is the code that I use. The `Connection` and the `Cursor` will automatically close thanks to `contextlib.closing()`. The `Connection` will automatically commit thanks to the context manager.

```
import sqlite3
import contextlib

def execute_statement(statement):
    with contextlib.closing(sqlite3.connect(path_to_file)) as conn: # auto-closes
        with conn: # auto-commits
            with contextlib.closing(conn.cursor()) as cursor: # auto-closes
                cursor.execute(statement)

```
Your version leaves conn in scope after connection usage.

EXAMPLE:

**your version**

```
    conn = sqlite3.connect(db_filename) #DECLARE CONNECTION OUT OF WITH BLOCK

    with conn:                          #USE CONNECTION IN WITH BLOCK
        cur = conn.cursor()
        cur.execute( ... )

   #conn variable is still in scope, so you can use it again

```

**new version** 

```
    with sqlite3.connect(db_filename) as conn:  #DECLARE CONNECTION AT START OF WITH BLOCK
        cur = conn.cursor()
        cur.execute( ... )   

   #conn variable is out of scope, so connection is closed 
   # MIGHT BE IT IS NOT CLOSED BUT WHAT  Avaris SAID!
   #(I believe auto close goes for with block)

```