Skip to content

Instantly share code, notes, and snippets.

@lucindo
Created August 30, 2010 18:55
Show Gist options
  • Save lucindo/557849 to your computer and use it in GitHub Desktop.
Save lucindo/557849 to your computer and use it in GitHub Desktop.
import sqlite3, contextlib, logging
# from: http://docs.python.org/library/sqlite3.html#sqlite3.Connection.row_factory
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
@contextlib.contextmanager
def db_connection(db_file):
con = sqlite3.connect(db_file)
con.row_factory = dict_factory
try:
yield con
con.commit()
except Exception, ex:
logging.error("database error - exception: %s" % str(ex))
finally:
con.close()
# ------------
# Using on some class...
# def get_all(self):
# result = []
# with db_connection(self._get_db()) as con:
# cur = con.cursor()
# cur.execute("select * from yoyo")
# for row in cur.fetchall():
# result.append(row)
# return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment