To handle connections with SQLite3 I studied the WITH
keyword and found out it is an alternative to try,except,finally
. It was said in case of file-handling, 'WITH' automatically handles closing files and I thought similar with the connection as said in zetcode tutorial:
"With the with keyword, the Python interpreter automatically releases the resources. It also provides error handling."
I couldn't figure out why both (inner scope and outer scope) statements work. Shouldn't WITH
release the connection?
import sqlite3
con = sqlite3.connect('test.db')
with con:
cur = con.cursor()
cur.execute('SELECT 1,SQLITE_VERSION()')
data = cur.fetchone()
print data
cur.execute('SELECT 2,SQLITE_VERSION()')
data = cur.fetchone()
print data
Which outputs:
(1, u'3.6.21')
(2, u'3.6.21')
I don't know what exactly WITH
is doing. Please elaborate on the use of WITH
over TRY CATCH
in this context. And should connections be opened and closed on each query (I am formulating queries inside a function which I call each time with an argument)?