Python pymysql fetchall() 结果作为字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4940670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pymysql fetchall() results as dictionary?
提问by Ricky
Is there any way to get the results from a fetchall() as a dictionary using pymysql?
有没有办法使用pymysql从fetchall()作为字典获取结果?
回答by d0nut
Use a DictCursorin the cursor() method.
在 cursor() 方法中使用DictCursor。
回答by Seun Osewa
PyMySQL includes a DictCursor. It does what I think you want. Here's how to use it:
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
https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/tests/test_DictCursor.py
回答by physicalattraction
If you mean that you want to fetch two columns, and return them as a dictionary, you can use this method.
如果您的意思是要获取两列,并将它们作为字典返回,则可以使用此方法。
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
回答by Mark Amery
Use pymysql.cursors.DictCursor, which will return rows represented as dictionaries mapping column names to values.
使用pymysql.cursors.DictCursor,它将返回表示为将列名称映射到值的字典的行。
A few ways to use it...
几种使用方法...
Create a connection object and have all cursors spawned from it be DictCursors:
创建一个连接对象并将所有游标从它生成为DictCursors:
>>> 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'}]
Create a DictCursorfrom an ordinary connection object:
DictCursor从一个普通的连接对象创建一个:
>>> connection = pymysql.connect(db='foo')
>>> with connection.cursor(pymysql.cursors.DictCursor) as cursor:
... print cursor
...
<pymysql.cursors.DictCursor object at 0x7f876830c050>
Connect and create a DictCursorin one line with with:
连接并DictCursor在一行中创建一个with:
>>> from pymysql.cursors import DictCursor
>>> with pymysql.connect(db='foo', cursorclass=DictCursor) as cursor:
... print cursor
...
<pymysql.cursors.DictCursor object at 0x7f8767769490>

