Last active
December 23, 2021 16:39
-
-
Save evan-burke/9b690d0df243b9bb0a72b3f8109b7465 to your computer and use it in GitHub Desktop.
simple python3 sqlite3 wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" This is pretty basic but makes it a little eaiser to use sqlite3 for common tasks. | |
Example usage: | |
db = sqlitelib(dbfile) | |
result = db.execute("select * from mytable") | |
or: | |
with sqlitelib(dbfile) as db: | |
result = db.execute("select * from mytable") | |
or supports sqlite3's uri functionality, enabling e.g., use in read-only mode. | |
db = sqlitelib('file:/path/to/dbfile?mode=ro', uri=True) | |
# see: https://docs.python.org/3/library/sqlite3.html#sqlite3.connect | |
# and: https://www.sqlite.org/uri.html | |
""" | |
import sqlite3 | |
class sqlitelib(object): | |
""" wrapper for sqlite3 providing some convenience functions. | |
Autocommit is on by default, and query results are lists of dicts. """ | |
def __init__(self, dbfile, uri=False): | |
self.dbfile = dbfile | |
self.conn = self.connect(uri=uri) | |
def __enter__(self): | |
return self #.__init__() | |
def connect(self, uri=False): | |
self.conn = sqlite3.connect(self.dbfile, isolation_level=None, uri=uri) | |
self.conn.row_factory = self.dict_factory | |
return self.conn | |
def execute(self, sql, parameters=None): | |
if not parameters: | |
c = self.conn.execute(sql) | |
else: | |
c = self.conn.execute(sql, parameters) | |
data = c.fetchall() | |
return data | |
def executemany(self, sql, parameters): | |
c = self.conn.executemany(sql, parameters) | |
data = c.fetchall() | |
return data | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.conn.close() | |
def close(self): | |
self.conn.close() | |
def dict_factory(self, cursor, row): | |
d = {} | |
for idx, col in enumerate(cursor.description): | |
d[col[0]] = row[idx] | |
return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment