数据库查询结果,用json返回:
#连接数据库 import pymysql print(pymysql.VERSION) conn = pymysql.Connect(host='localhost',user='root',passwd='qin',db='person',port=3306,charset='utf8') cur = conn.cursor() cur.execute("select * from dream") print (cur.rowcount)
数据库查询结果,用json返回:
#数据库查询结果,用json返回 import json import pymysql conn = pymysql.Connect(host='localhost',user='root',passwd='python',db='zzdb',port=3306,charset='utf8') cur = conn.cursor() cur.execute("select * from users") print ('共有',cur.rowcount,'条数据') users=[] data = {} results = cur.fetchall() for r in results: print(r[0],end=' ') print(r[1],end=' ') print(r[2],end=' ') print("---") person = {} person['id'] = r[0] person['name'] = r[1] person['age'] = r[2] users.append(person) cur.close() conn.close() data['code'] = 0 data['msg'] = '成功' data['users'] = users jsonStr = json.dumps(data) print(jsonStr)
输出json
#将一个list列表对象,进行了json格式的编码转换 import json l = ['iplaypython',[1,2,3], {'name':'xiaoming'}] encoded_json = json.dumps(l) #将列表,进行json格式化编码 print (repr(l)) print (encoded_json) decode_json = json.loads(encoded_json) print (type(decode_json)) print (type(encoded_json))
..