Created
August 30, 2010 18:55
-
-
Save lucindo/557849 to your computer and use it in GitHub Desktop.
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
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