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

本文介绍了如何使用PyMySQL库从数据库中获取所有数据,并将其转换为字典格式,以便直接用于API结果的JSON转换。通过配置连接以使用DictCursor类,可以轻松地将查询结果转化为字典,从而简化数据处理过程。
摘要由CSDN通过智能技术生成

I was able to get a single data from a table. but when i'm trying to get all the data on my table, i got only a single row.

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

解决方案

Now, in PyMysql, there is a facility to configure your connection to use the cursorClass which by default generates Dictionary as the output. (And thus works directly when returning in the API result as it gets converted to JSON)

From the documentation of PyMysql: Configure your connection as

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

Output for this result :

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值