我目前正在这样做:
cursor.execute('SELECT thing_id, thing_name FROM things')
things = [];
for row in cursor.fetchall():
things.append(dict([('thing_id',row[0]),
('thing_name',row[1])
]))
我可以用一些简写来做这个,还是应该写一个小帮手功能?
答案 0 :(得分:4)
things = [{'thing_id': row[0], 'thing_name': row[1]} for row in cursor.fetchall()]
或使用zip
列表理解:
things = [dict(zip(['thing_id', 'thing_name'], row)) for row in cursor.fetchall()]
如果您使用Cursor.description
attribute,则可以获取列名称:
names = [d.name for d in c.description]
things = [dict(zip(names, row)) for row in cursor.fetchall()]
答案 1 :(得分:3)
通过将游标类传递给MySQLdb.cursors.DictCursor
方法,您可以使用MySQLdb.cursors.Cursor
类而不是cursor
:
In [9]: cur = conn.cursor(MySQLdb.cursors.DictCursor)
In [10]: cur.execute('SELECT * FROM test_table')
Out[10]: 3L
In [11]: cur.fetchall()
Out[11]:
({'create_time': datetime.datetime(2015, 12, 2, 10, 22, 23),
'id': 1L,
'name': 'Bob'},
{'create_time': datetime.datetime(2015, 12, 2, 10, 22, 34),
'id': 2L,
'name': 'Stive'},
{'create_time': datetime.datetime(2015, 12, 2, 10, 22, 37),
'id': 3L,
'name': 'Alex'})