pymysql fetchall()结果为字典?

时间:2011-02-09 02:14:59

标签: python mysql

有没有办法使用pymysql将fetchall()的结果作为字典?

4 个答案:

答案 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