1. 程式人生 > 其它 >python 資料庫查詢,將查詢的列名也儲存下來,返回字典型別的資料

python 資料庫查詢,將查詢的列名也儲存下來,返回字典型別的資料

前言:

python + pymysql:通過pymysql,查詢到符合要求的資料,不做型別轉化的,返回的時元組型別的資料,可以根據下標,取想要的值。

self.cursor.execute(sql)
# 返回的是元組,可根據需要只查詢對應的引數來取參使用 result = self.cursor.fetchall()

後續使用,如果有些方法需要判斷某個值,是否存在的時候,每條sql都不同,不能簡單的通過下標來取值,如果可以根據當前資料的key來判斷,有沒有資料,就不用擔心具體是哪一個下標了

# 返回來的資料,通過下標,來指定取第幾個值
user_name = self.handel_username(str(user[0
]), str(user[1]))

解決方案,將查詢出來的列名和資料,轉化成字典型別,這樣就可以根據key來取值

        try:
            self.connect_dbserver()
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
            # 查出當前查詢的列名,儲存到coloums
            coloums = [column[0] for column in self.cursor.description]
            
# 定義一個數組,用來儲存每一組的陣列,格式為字典形式{"name":"test","age":18} sub_resdata = [] for row in res: # 迴圈遍歷查詢出來的結果,然後生成字典 res_data = dict(zip(coloums, row)) sub_resdata.append(res_data) except Exception as e: mylog.exception(
"查詢資料出錯,請檢查{0}".format(e)) return sub_resdata

最後,就可以根據具體的key來取值了

res = DoMysql('').get_data_return_dict(sql)
print(res[0]["moblie"])

參考文章:https://www.cnblogs.com/xyao1/p/10694819.html