pymysql fetchall() results as dictionary?

前端 未结 4 1944
执念已碎
执念已碎 2020-12-02 15:26

Is there any way to get the results from a fetchall() as a dictionary using pymysql?

4条回答
  •  死守一世寂寞
    2020-12-02 16:04

    Use pymysql.cursors.DictCursor, which will return rows represented as dictionaries mapping column names to values.

    A few ways to use it...

    Create a connection object and have all cursors spawned from it be DictCursors:

    >>> import pymysql
    >>> connection = pymysql.connect(db='foo', cursorclass=pymysql.cursors.DictCursor)
    >>> with connection.cursor() as cursor:
    ...     print cursor
    ... 
    
    >>> 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 DictCursor from an ordinary connection object:

    >>> connection = pymysql.connect(db='foo')
    >>> with connection.cursor(pymysql.cursors.DictCursor) as cursor:
    ...     print cursor
    ... 
    

    Connect and create a DictCursor in one line with with:

    >>> from pymysql.cursors import DictCursor
    >>> with pymysql.connect(db='foo', cursorclass=DictCursor) as cursor:
    ...     print cursor
    ... 
    
    

提交回复
热议问题