L1.2.1 sqlite程序(返回字典形式),

一.返回值爲字典形式
原[(1, “小明”), (2, “小紅”)]
需求[{“id”:1, “name”:“小明”},{“id”:2, “name”:“小紅”}]

百度後思路

  1. 驅動方法: https://www.jb51.net/article/94024.htm cursor.description()
  2. 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())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章