L1 2 1 sqlite程式 返回字典形式 ,

2021-08-31 21:36:43 字數 1658 閱讀 6148

一.返回值為字典形式

原[(1, 「小明」), (2, 「小紅」)]

需求[,]

驅動方法: cursor.description()

sql語句 :

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', '***', 'phone']

description = cursor.description

# 獲得游標所在表的資訊 包含列名

column_name_list =

for i in description: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)

# print

(result)

# print

('*****************語法糖寫法'

)print([

dict

(zip

(column_name_list, employee)

)for employee in employees]

)#

返回字典—官方版》

import sqlite3

defdict_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(

))

sqlalchemy 這原生sql中繫結list

這專案中有在一定範圍內進行更新的要求,所以直接使用sqlalchemy執行sql語句進行更新,但是發現list無法繫結到引數上。stack overflow上查詢到了解決方案,將list轉成tuple才能進行繫結 示例 id list 1,2,3 sql text update test set n...