I'm trying to use the "with" contextmanager using pysqlite:
>>> with conn.cursor() as db:
res = db.execute("SELECT * FROM Publishers LIMIT 5;").fetchall()
... ... Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __enter__
I see that the __enter__
and __exit__
methods are not defined, so a with
contextmanager won't be available.
I also understand from the pysqlite documentation that the sqlite3 is a little quirky with respect to connections. In general, I would prefer use the context manager with python DB APIs per idiomatic python.
Does this suggest that I /should not/ try overloading and achieving a context manager? That there's something in the sqlite3 bindings that make this not advisable or not idiomatic?
Does this mean proper usage would be instantiating my cursor only one time (db = conn.cursor()
) as a global and calling it (db.execute(query,params)
) in each of my functions? Or that I must re-instantiate, call, and close the db in every function (db = conn.cursor(); db.query(query,params); db.close()
and do so verbosely, lacking the context manager?