python内部是以tuple格式存储的关系型数据库的查询结果,在实际的使用过程中可能需要转换成list或者dict,json等格式。在这里讲解如何将查询的结果转成json字符串。这里需要导入numpy、pandas、json包
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 4 5 import json 6 import numpy as np 7 import pandas as pd 8 9 import AppSetting.dbConfig as db 10 11 try: 12 sql = "select * from el_catalog where parentid='0' order by itemorder"; 13 df = pd.read_sql(sql, db.pd_connect + 'yw_collection') 14 # 获取列名 15 column_list = list(df.columns) 16 df1 = np.array(df) 17 18 lst = [] 19 for row in df1: 20 # 循环每一行数据,组装成一个字典,然后得到字典的列表 21 lst.append(dict(zip(column_list, list(row)))) 22 # 导入json,将列表转为json字符串 23 # son.dumps序列化时候对中文默认使用的ascii编码,想要输出真正的中文需要指定ensure_ascii=False 24 str1 = json.dumps(lst, ensure_ascii=False) 25 print(str1) 26 except Exception as ex: 27 print(ex)
查询结果:
[{"Id": 1, "Name": "人员", "ParentId": "0", "ItemOrder": 1}, {"Id": 2, "Name": "企业", "ParentId": "0", "ItemOrder": 2}, {"Id": 3, "Name": "工程", "ParentId": "0", "ItemOrder": 3}]