1. 程式人生 > >sqlite3 設定返回值為字典形式

sqlite3 設定返回值為字典形式

首先是官方的方法

# 匯入驅動
import sqlite3

def dict_factory(cursor, row):
    d = {}
    for index, col in enumerate(cursor.description):
        d[col[0]] = row[index]
    return d

# 連線資料庫
connect = sqlite3.connect("testsqlite.db")

# 指定工廠方法
connect.row_factory = dict_factory
cursor = connect.cursor()
cursor.execute("SELECT * FROM student") rows = cursor.fetchall() print(rows) for row in rows: print(row) # 提交操作 connect.commit() # 關閉遊標 cursor.close() # 關閉資料庫連線 connect.close()

另一種方法

import sqlite3
connect = sqlite3.connect("testsqlite.db")
cursor = connect.cursor()

cursor.execute("""SELECT * FROM employee;"""
) employees = cursor.fetchall() # print(employees) # 獲得列名 # print(cursor.description) description = cursor.description # 獲得遊標所在表的資訊 包含列名。 column_name_list = [] for i in description: column_name_list.append(i[0]) # print(column_name_list) print("-" * 50) # 結果集拼字典 result = [] for employee in employees:
employee_dict = {} for index in range(0, len(column_name_list)): # print(employee[index]) employee_dict[column_name_list[index]] = employee[index] # print(employee_dict) result.append(employee_dict) # print(dict(zip(column_name_list, employee))) # print(result) # 語法糖 列表生成式 print([dict(zip(column_name_list, employee)) for employees in employees])