更簡單的方式移步:連接mysql獲取帶列名的數據
使用pymysql連接數據庫進行查詢時,獲取的只是查詢的結果,並不包含列名。
可以使用cursor.description來獲取列名的相關信息。執行結果如下所示。
#!/usr/bin/env/python # -*- coding:utf-8 -*- import pymysql import pandas as pd import time def execude_sql(sql): # 創建連接 try: db = pymysql.connect(host='127.0.0.1', port=3308, user='name', passwd='password', db='db', charset='utf8') except: print('數據庫連接失敗,10s后重試') time.sleep(10) # 創建游標 cursor = db.cursor() cursor.execute(sql) col = cursor.description result = cursor.fetchall() #執行結果轉化為dataframe df = pd.DataFrame(list(result)) # 關閉連接 db.close() #返回dataframe return result,col sql1 = """select comment_sql from etl_event_head where event_id=6001""" resu,co = execude_sql(sql1) for (test,) in resu: result,col = execude_sql(test) print(result) print(col[1][0]) print(col)
執行結果:
(('40102', 'cp_tt2fre', '聯系人→進件', '6%', '低於80%'), ('4105', 'cp_orders', '單卡→生成訂單', '3%', '低於5%'))
預警類型編碼
(('ERROR_CODE', 253, None, 92, 92, 0, True), ('預警類型編碼', 253, None, 144, 144, 0, False), ('預警說明', 253, None, 192, 192, 0, True), ('指標率', 253, None, 76, 76, 0, True), ('閾值說明', 253, None, 192, 192, 0, True))
如果想獲取字段列表,遍歷一下元組即可。
list = [] for i in range(len(col)): list.append(col[i][0]) print(list)
輸出
['ERROR_CODE', '預警類型編碼', '預警說明', '指標率', '閾值說明']