Connect to Database so it Returns Lists of Dictionaries instead of Lists of Lists

Table of Contents

Header#

import sys
import sqlite3
import MySQLdb

SQLite#

try:
    sqlite_conn = sqlite3.connect('database.sqlite')
    sqlite_conn.row_factory = sqlite3.Row
    sqlite_conn.text_factory = str
except NameError, ex:
    print 'Could not connect to database: %s' % str(ex)
    sys.exit()
except Exception, ex:
    print 'Unexpected error: %s : %s' % (str(type(ex)), ex)
    sys.exit()
sqlite_cursor = sqlite_conn.cursor()
print 'Connected to sqlite'

MySQL#

try:
    mysql_conn = MySQLdb.connect(host='localhost', 
        db='db_name', user='username', passwd='password',
        cursorclass=MySQLdb.cursors.DictCursor, 
        use_unicode=True, charset='utf8')
except NameError, ex:
    print 'Could not connect to database: %s' % str(ex)
    sys.exit()
except Exception, ex:
    print 'Unexpected error: %s : %s' % (str(type(ex)), ex)
    sys.exit()
mysql_cursor = mysql_conn.cursor()
print 'Connected to MySQL'

Python - SQL - MySQL