有时我们可能会想要数据库查询结果中带有字段名。比如使用的是pymysql引擎。
conn = pymysql.connect(host=‘127.0.0.1‘, user=‘root‘, password=‘123456‘, database=‘python_test‘, charset=‘utf8‘) cursor = conn.cursor() sql = "select * from user" cursor.execute(sql) result = cursor.fetchall()
正常的获取到的结果是不带字段名的,结果如下:
((zhangsan, 23), (lisi, 24), (wangwu, 25))
但是如果在获取连接的connect()函数中加一个参数,cursor=pymysql.cursors.DictCursor, 则会在查询结果中带上字段名,
conn = pymysql.connect(host=‘127.0.0.1‘, user=‘root‘, password=‘123456‘, database=‘python_test‘, charset=‘utf8‘, cursor=pymysql.cursors.DictCursor) cursor = conn.cursor() sql = "select * from user" cursor.execute(sql) result = cursor.fetchall()
查询结果如下:
[{‘username‘:‘zhangsan‘, ‘age‘:23}, {‘username‘:‘lisi‘, ‘age‘:24},{‘username‘:‘wangwu‘, ‘age‘:25},]