SQL查询返回元组中的输出,其中{key:value}对中缺少键(列名)



我想以key:value格式从数据库表中检索数据。但通过使用SQL查询,我只能获得元组格式的值。

这是我的代码:

query = "SELECT * FROM `stock_" + str(
user_id) + "` INNER JOIN product ON stock_" + str(
user_id) + ".product_id=product.id WHERE product.category=" + category + 
" AND product.sub_category =" + sub_category
cursor.execute(query)
records = cursor.fetchall()
print(records)

输出如下:

(11, datetime.datetime(2020, 1, 23, 2, 7, 59),10,500,400,100,20.0)

以及我的预期输出:

{
"id": 11,
"expiry_date": "2020-07-01",
"quantity": 10,
"mrp": 500,
"selling_price": 400,
"discount_prize": 100,
"discount_percent": 20.0
}

您可以使用cursor.description来获取字段名称,然后可以使用列表理解来创建一个包含查询结果的字典列表。

这应该会给你一些接近你想要的输出的东西。

records = cursor.fetchall()
fields = [field[0] for field in cursor.description]
data = [dict(zip(fields, record))  for record in records]

最新更新