This is supposed to work yet just says no stocks table – supposed lost the connection somewhere inside the contextmanager?
import sqlite3
from contextlib import contextmanager
@contextmanager
def doquery(conn, q, params=()):
c = conn.cursor()
c.execute(q, params)
conn.commit()
yield c
c.close()
with sqlite3.connect(':memory:') as db:
doquery(db,'''create table stocks
(date text, trans text, symbol text,
qty real, price real)''')
doquery(db,"""insert into stocks
values ('2006-01-05','BUY','RHAT',100,35.14)""")
with doquery(db, 'select * from stocks') as r:
for row in r:
print row
The problem is with the way you are using the context manager. Calling
doquerysimply creates a context manager object – you need to use it within awithstatement, which calls its__enter__and__exit__methods as appropriate. For example, try the following:The output I get is:
You might want to re-read the documentation about the with statement and contextlib.
Another problem with your code is that if
c.executeorconn.commitraises an exception,c.closewill not be called – I don’t know if that is actually necessary, but presumably it is the reason why you want to use a context manager rather than a function in the first place. The following changes should fix both problems:However, I don’t think this is the cleanest way of doing this. As far as I can see, there is no reason to create three separate
cursorobjects – you can use the same one for each query. I don’t think the call toconn.commitis actually necessary either – using the database connection as a context manager will automatically commit transactions, or roll them back if an exception is raised (see the sqlite3 module documentation).EDIT: Here is a much cleaner version, which still works. I really don’t know what closing the cursor actually does though – it probably isn’t necessary (
Cursor.closedoesn’t even seem to be documented).