2010-11-10 11 views
16

Wenn ich sowas tun wiePython - MySQLdb, SQLite Ergebnis als Wörterbuch

sqlite.cursor.execute("SELECT * FROM foo") 
result = sqlite.cursor.fetchone() 

Ich denke, haben die Reihenfolge der Spalten zu erinnern scheinen der Lage zu sein, sie heraus zu holen, zB

result[0] is id 
result[1] is first_name 

ist Gibt es eine Möglichkeit, ein Wörterbuch zurückzugeben? also kann ich stattdessen einfach result ['id'] oder ähnliches verwenden?

Das Problem mit den nummerierten Spalten ist, wenn Sie Ihren Code schreiben, dann fügen Sie eine Spalte ein.

+0

Mögliche Duplikat [Wie kann ich von SQLite-Abfrage dict bekommen?] (Http://stackoverflow.com/questions/3300464/how-can-i-get-dict-from-sqlite -Abfrage) Geht es um SQLite oder MySQL? –

Antwort

5

David Beazley hat ein schönes Beispiel dafür in seinem Python Essential Reference.
Ich habe das Buch nicht zur Hand, aber ich denke, sein Beispiel so etwas wie diese:

def dict_gen(curs): 
    ''' From Python Essential Reference by David Beazley 
    ''' 
    import itertools 
    field_names = [d[0].lower() for d in curs.description] 
    while True: 
     rows = curs.fetchmany() 
     if not rows: return 
     for row in rows: 
      yield dict(itertools.izip(field_names, row)) 

Verwendungsbeispiel:

>>> import sqlite3 
>>> conn = sqlite3.connect(':memory:') 
>>> c = conn.cursor() 
>>> c.execute('create table test (col1,col2)') 
<sqlite3.Cursor object at 0x011A96A0> 
>>> c.execute("insert into test values (1,'foo')") 
<sqlite3.Cursor object at 0x011A96A0> 
>>> c.execute("insert into test values (2,'bar')") 
<sqlite3.Cursor object at 0x011A96A0> 
# `dict_gen` function code here 
>>> [r for r in dict_gen(c.execute('select * from test'))] 
[{'col2': u'foo', 'col1': 1}, {'col2': u'bar', 'col1': 2}] 
4

Sie diese einfach sehr tun können. Für SQLite: my_connection.row_factory = sqlite3.Row

Check it auf der Python-Dokumentation aus: 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 darwin 
Type "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 foo 
2 bar 
+0

Dank @Adam für das interaktive Beispiel. –

11

Dadurch in MySQLdb Sie fügen Sie einfach den folgenden in den Verbindungsfunktionsaufruf

cursorclass = MySQLdb.cursors.DictCursor 
1

Eine sqlite3.Row-Instanz kann in dict konvertiert werden - sehr praktisch, um ein Ergebnis als j auszugeben

Sohn
>>> csr = conn.cursor() 
>>> csr.row_factory = sqlite3.Row 
>>> csr.execute('select col1, col2 from test') 
>>> json.dumps(dict(result=[dict(r) for r in csr.fetchall()])) 
+1

das gibt mir ein 'Wörterbuch Update Sequenzelement # 0 hat die Länge 15; 2 ist erforderlich' – Tobi

29
import MySQLdb 
dbConn = 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.close 
dbConn.close() 
+0

Danke, es funktioniert. – swietyy

+0

Gibt es eine Möglichkeit, die Zeilen, die von einem 'DictCursor' abgerufen werden, in' 'set()' einzufügen, ohne in 'TypeError: unshashable type: 'dict'' zu laufen? – ray

+1

Dies sollte die richtige und akzeptierte Antwort sein. –