有没有办法使用pymysql将fetchall()的结果作为字典?
答案 0 :(得分:71)
PyMySQL包含DictCursor
。它做我认为你想要的。以下是如何使用它:
import pymysql
connection = pymysql.connect(db="test")
cursor = connection.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT ...")
https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/tests/test_DictCursor.py
答案 1 :(得分:27)
使用pymysql.cursors.DictCursor
,它将返回表示为将列名称映射为值的字典的行。
使用它的几种方法......
DictCursor
s:>>> import pymysql
>>> connection = pymysql.connect(db='foo', cursorclass=pymysql.cursors.DictCursor)
>>> with connection.cursor() as cursor:
... print cursor
...
<pymysql.cursors.DictCursor object at 0x7f87682fefd0>
>>> with connection.cursor() as cursor:
... cursor.execute("SELECT * FROM bar")
... print cursor.fetchall()
...
2
[{u'col2': 'rty', u'col1': 'qwe'}, {u'col2': 'fgh', u'col1': 'asd'}]
DictCursor
:>>> connection = pymysql.connect(db='foo')
>>> with connection.cursor(pymysql.cursors.DictCursor) as cursor:
... print cursor
...
<pymysql.cursors.DictCursor object at 0x7f876830c050></code></pre>
DictCursor
with
>>> from pymysql.cursors import DictCursor
>>> with pymysql.connect(db='foo', cursorclass=DictCursor) as cursor:
... print cursor
...
<pymysql.cursors.DictCursor object at 0x7f8767769490>
答案 2 :(得分:3)
在cursor()方法中使用DictCursor。
答案 3 :(得分:0)
如果您想要获取两列,并将它们作为字典返回,则可以使用此方法。
def fetch_as_dict(cursor select_query):
'''Execute a select query and return the outcome as a dict.'''
cursor.execute(select_query)
data = cursor.fetchall()
try:
result = dict(data)
except:
msg = 'SELECT query must have exactly two columns'
raise AssertionError(msg)
return result