Pymysql DictCursor返回列表而不是字典

时间:2019-03-11 05:59:20

标签: python sql pymysql

我试图弄清楚为什么这个查询返回的是列表列表而不是字典列表。我怀疑这与查询的联接或“ as”部分有关。任何对此的见识将不胜感激。

下面的代码:

   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())

按执行顺序返回:

第一个:词典列表,该查询与我期望的column_name:value相匹配。

第二:这样的列表(('63741','7598.7924528302',merchant_id,'store_name'),)

1 个答案:

答案 0 :(得分:2)

尝试:

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

我将游标类型更改为connect方法之内