Skip to content

Instantly share code, notes, and snippets.

Last active November 30, 2022 20:31
  • Star 17 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Simple sqlite3 context manager for Python.
#!/usr/bin/env python
import sqlite3
class dbopen(object):
Simple CM for sqlite3 databases. Commits everything at exit.
def __init__(self, path):
self.path = path
def __enter__(self):
self.conn = sqlite3.connect(self.path)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_class, exc, traceback):
if __name__ == '__main__':
with dbopen('./sample.db') as c:
c.execute("CREATE TABLE seekmap (id text, offset int, length int)")
c.execute("INSERT INTO seekmap VALUES ('a', 0, 2000)")
c.execute("INSERT INTO seekmap VALUES ('b', 2000, 3000)")
c.execute("SELECT * FROM seekmap")
result = c.fetchall()
# [(u'a', 0, 2000), (u'b', 2000, 3000)]
Copy link

self .conn = None
self .cursor = None


Copy link

miku commented Dec 11, 2019

@Glukhov555, you're right, it's not necessary - I changed the code. I'd say it would be ok to document the attributes in the constructor.

Copy link

need to mark that it is not necessary but, for the understanding of how it is taken would not be bad

Copy link

Thank you for that.

Copy link

Thank you!

Copy link

fwarren commented Nov 23, 2021

I have made a gist with this updated to have type hinting fwarren / and to pass linting. __init__ needs self.conn and self.cursor but they are not initalized, only type hinted.

self.conn: Connection
self.cursor: Cursor

In actual practice you can typehint execute(), fetchall(), fetchmany() and fetchone() with:

result: Cursor = c.execute()
result: list[Any] = c.fetchall()
result: list[Any] = c.fetchmany()
result: Any = c.fetchone()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment