Python - mysqlDB, sqlite result as dictionary Python - mysqlDB, sqlite result as dictionary python python

Python - mysqlDB, sqlite result as dictionary


import MySQLdbdbConn = MySQLdb.connect(host='xyz', user='xyz', passwd='xyz', db='xyz')dictCursor = dbConn.cursor(MySQLdb.cursors.DictCursor)dictCursor.execute("SELECT a,b,c FROM table_xyz")resultSet = dictCursor.fetchall()for row in resultSet:    print row['a']dictCursor.closedbConn.close()


Doing this in mysqlDB you just add the following to the connect function call

cursorclass = MySQLdb.cursors.DictCursor


You can do this very easily. For SQLite: my_connection.row_factory = sqlite3.Row

Check it out on the python docs: http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index

UPDATE:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> import sqlite3>>> conn = sqlite3.connect(':memory:')>>> conn.row_factory = sqlite3.Row>>> c = conn.cursor()>>> c.execute('create table test (col1,col2)')<sqlite3.Cursor object at 0x1004bb298>>>> c.execute("insert into test values (1,'foo')")<sqlite3.Cursor object at 0x1004bb298>>>> c.execute("insert into test values (2,'bar')")<sqlite3.Cursor object at 0x1004bb298>>>> for i in c.execute('select * from test'): print i['col1'], i['col2']... 1 foo2 bar