Skip to content
Advertisement

Pymysql DictCursor returning list rather than dictionary

I am trying to figure out why this query is returning a list of lists rather than a list of dictionaries. I suspect it has something to do with either the join or the ‘as’ portion of the query. Any insight into this would be appreciated.

Code Below:

   try:
        #Connect to database
        connection = pymysql.connect(
            dbConfig.host,
            user=dbConfig.user,
            passwd=dbConfig.password,
            db=dbConfig.db,
            ssl=dbConfig.ssl,
            connect_timeout=5
            )
        cursor = connection.cursor(pymysql.cursors.DictCursor)
        print(cursor)

    except Exception:
        print("Error connecting to db")
        return

    sql = ('select retsub.sms_credits as sms_balance, '
        'retsub.subscription_credit as mms_balance, '
        'mg.merchants_id, '
        'mg.store_name, '
        'mg.email_representative from mg_groupdeals_merchants mg '
        'left join mg_giftdigital_retailer_retailersubscription retsub on (mg.merchants_id=retsub.merchant_id) '
        'left join mg_api_event_mapping event on(mg.merchants_id=event.merchant_id) '
        'where retsub.sms_credits is not null '
        'and event.merchant_id is not null '
        'group by merchants_id;')

    cursor.execute('select * from mg_giftdigital_user_sessions')
    print(cursor.fetchall())
    cursor.execute(sql)
    print(cursor.fetchall())

Which returns in order of execution:

First: A list of dictionaries matching the query with column_name:value, which is what I expect.

Second: A list like this ((‘63741’, ‘7598.7924528302’, merchant_id, ‘store_name’),)

Advertisement

Answer

Try:

connection = pymysql.connect(
        dbConfig.host,
        user=dbConfig.user,
        passwd=dbConfig.password,
        db=dbConfig.db,
        ssl=dbConfig.ssl,
        connect_timeout=5
        cursorclass=pymysql.cursors.DictCursor
        )

I changed the cursor type to be inside the connect method

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement