python使用pymysql查询结果返回json
pymysql转json关键参数 cursorclass=cursors.DictCursor
案例
import pymysql
from pymysql import cursors
def sql_json():
con = pymysql.connect(host=‘127.0.0.1’, user='oo', password='123456', port=3306,db='myuser',cursorclass=cursors.DictCursor)
cur = con.cursor()
sql = "select id,username from user_info "
cur.execute(sql)
all_obj = cur.fetchall()
print(all_obj, '\n', type(all_obj[0]))
cur.close()
con.close()
if __name__ == '__main__':
sql_json()
返回案例
[{'id': 1, 'username': '123'}, {'id': 2, 'username': 'hou'}, {'id': 3, 'username': 'lihuidu'}, {'id': 4, 'username': 'test1'}, {'id': 5, 'username': 'wangyameng'}, {'id': 6, 'username': 'ljh'}]
<class 'dict'>
无cursorclass=cursors.DictCursor 参数返回案例
((1, '123'), (2, 'hou'), (3, 'lihuidu'), (4, 'test1'), (5, 'wangyameng'), (6, 'ljh'))
<class 'tuple'>
|