一.返回值爲字典形式
原[(1, “小明”), (2, “小紅”)]
需求[{“id”:1, “name”:“小明”},{“id”:2, “name”:“小紅”}]
百度後思路
- 驅動方法: https://www.jb51.net/article/94024.htm cursor.description()
- sql語句 : http://www.hangge.com/blog/cache/detail_1454.html
PRAGMA table_info([employee]);
import sqlite3
connect = sqlite3.connect("testsqlite.db")
cursor = connect.cursor()
cursor.execute(" select * from employee; ")
employees = cursor.fetchall()
print(employees) # [(1, '小明', '男', '13600000000')]
print(cursor.description) # ['id', 'name', 'sex', 'phone']
description = cursor.description
# 獲得遊標所在表的信息 包含列名
column_name_list = []
for i in description:
column_name_list.append(i[0]) # 列名
print('*' * 20)
# 結果集拼字典
result = []
for employee in employees:
tem_dict = {}
for index in range(0, len(column_name_list)):
tem_dict[column_name_list[index]] = employee[index]
print(tem_dict) # {'id': 1, 'name': '小明', 'sex': '男', 'phone': '13600000000'}
result.append(tem_dict)
print(result) # [{'id': 1, 'name': '小明', 'sex': '男', 'phone': '13600000000'}]
print('*****************語法糖寫法')
print([dict(zip(column_name_list, employee)) for employee in employees])
# [{'id': 1, 'name': '小明', 'sex': '男', 'phone': '13600000000'}]
返回字典—官方版>
import sqlite3
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
connect = sqlite3.connect("testsqlite.db")
connect.row_factory = dict_factory
cursor = connect.cursor()
cursor.execute(" select * from employee; ")
print(cursor.fetchall())