如何获取所有mysql元组结果并转换为json

2024-09-25 02:24:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我能从一张表中得到一个数据。但当我试图获取表中的所有数据时,我只有一行。

cnn.execute(sql)
        rows = cnn.fetchall()
        column = [t[0] for t in cnn.description]
        for row in rows:
            myjson = {column[0]: row[0], column[1]: row[1], column[2]: row[2], column[3]: row[3], column[4]: row[4], column[5]: row[5], column[6]: row[6], column[7]: row[7], column[8]: row[8], column[9]: row[9], column[10]: row[10], column[11]: row[11], column[12]: row[12], column[13]: row[13], column[14]: row[14], column[15]: row[15], column[16]: row[16], column[17]: row[17], column[18]: row[18], column[19]: row[19], column[20]: row[20]}
            myresult = json.dumps(myjson, indent=3)
            return myresult

Tags: 数据injsonforexecutesqlcolumndescription
3条回答

不需要指定“硬编码”键值映射,请改用zip()(或itertools.izip())。

另外,收集列表中的行,然后将结果转储到json:

def dictfetchall(cursor):
    """Returns all rows from a cursor as a list of dicts"""
    desc = cursor.description
    return [dict(itertools.izip([col[0] for col in desc], row)) 
            for row in cursor.fetchall()]

用法:

results = dictfetchall(cursor)
json_results = json.dumps(results)

希望能有所帮助。

return语句在for循环中,因此在一次迭代之后,它将立即返回值为myresult

现在,在PyMysql中,有一个工具可以将连接配置为使用cursorClass,默认情况下,cursorClass会生成字典作为输出。(因此,当API结果转换为JSON时直接返回时,它就可以工作)

从PyMysql的documentation中:将连接配置为

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

result = cursor.fetchone()
        print(result)

此结果的输出:

{'password': 'very-secret', 'id': 1}

相关问题 更多 >