1. 程式人生 > >pymysql獲取要查詢的欄位名(列名)

pymysql獲取要查詢的欄位名(列名)

使用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', '預警型別編碼', '預警說明', '指標率', '閾值說明']