我能从一张表中得到一个数据。但当我试图获取表中的所有数据时,我只有一行。
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
不需要指定“硬编码”键值映射,请改用
zip()
(或itertools.izip())。另外,收集列表中的行,然后将结果转储到json:
用法:
希望能有所帮助。
return语句在for循环中,因此在一次迭代之后,它将立即返回值为
myresult
。现在,在PyMysql中,有一个工具可以将连接配置为使用cursorClass,默认情况下,cursorClass会生成字典作为输出。(因此,当API结果转换为JSON时直接返回时,它就可以工作)
从PyMysql的documentation中:将连接配置为
此结果的输出:
相关问题 更多 >
编程相关推荐