python3使用mysql.connector包如何實(shí)現(xiàn)返回字典類(lèi)型數(shù)據(jù)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", # 數(shù)據(jù)庫(kù)主機(jī)地址
user="root", # 數(shù)據(jù)庫(kù)用戶(hù)名
passwd="root", # 數(shù)據(jù)庫(kù)密碼
database="gaoyu"
)
mycursor = mydb.cursor(dictionary=True)
mycursor.execute("SELECT names,sex FROM student")
myresult = mycursor.fetchone() # fetchone() 獲取所有記錄
print(myresult)加上dictionary=True就能實(shí)現(xiàn)返回字典類(lèi)型數(shù)據(jù)
去掉dictionary=True,查詢(xún)返回就是一個(gè)元組,沒(méi)有key,只有value
字典類(lèi)型:
{'names': '小小測(cè)試', 'sex': '男'}
而元組如下形式:
('小小測(cè)試', '男')
