python-pymysql獲取字段名稱-獲取內(nèi)容方式
更新時(shí)間:2023年05月08日 09:50:13 作者:L'y
這篇文章主要介紹了python-pymysql獲取字段名稱-獲取內(nèi)容方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
python-pymysql獲取字段名稱-獲取內(nèi)容
獲取字段名稱-獲取內(nèi)容
import pymysql # 連接數(shù)據(jù)庫 db = pymysql.connect(host='192.168.254.109', user='root', password='123456', database='blog') # 使用cursor()方法創(chuàng)建一個(gè)游標(biāo)對象 cursor = db.cursor() # ?查詢語句 sql = """select * from a""" # 執(zhí)行 sql語句 cursor.execute(sql) # 查詢?nèi)? results = cursor.fetchall() # 獲取表結(jié)構(gòu) ?cursor.description fields = [field[0] for field in cursor.description] # 序列化 成字典 zip ?把兩個(gè)可迭代對象合并成2維元組。然后用dict 轉(zhuǎn)化為字典。 res = [dict(zip(fields, result)) for result in results] print(res) # 關(guān)閉游標(biāo)和數(shù)據(jù)庫的連接 cursor.close() db.close() pro_res = """ [{'id': 1, 'name': '111', 'create_time': datetime.datetime(2022, 1, 6, 11, 6, 42), 'update_time': datetime.datetime(2022, 1, 6, 11, 6, 42)}, ? ? ? ? ? ?{'id': 2, 'name': '222', 'create_time': datetime.datetime(2022, 1, 6, 11, 36, 4), 'update_time': datetime.datetime(2022, 1, 6, 11, 36, 4)}]"""
若只執(zhí)行 results = cursor.fetchall()
1 產(chǎn)出的結(jié)果都是 元組 且不包含字段名稱的.
2 使用pandas去解析這個(gè) results也無法產(chǎn)出字段的.
python代碼獲取mysql字段名和注釋
# coding=utf-8 import pymysql def get_mysql_zi_duan(): conn = pymysql.connect(host='192.168.', port=3306, user='hs', passwd='xi', db='db_x', charset='utf8') cursor01 = conn.cursor() cursor01.execute( "select column_name, column_comment from information_schema.columns where table_schema ='db_xingyun' and table_name = 'api_ind_guan_yi_s_d'") all_info = cursor01.fetchall() # 數(shù)據(jù)庫字段名和注釋 # print(all_info) zi_duan_ming = [] zhushi = [] for data in all_info: zi_duan_ming.append(data[0]) zhushi.append(data[1]) # print(data[0]) print(str(zi_duan_ming).replace('[','').replace(']','').replace("'",'')) print(zhushi) cursor01.close() conn.close() if __name__ == '__main__': # 獲取一個(gè)表的 所有字段名 get_mysql_zi_duan()
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Python pymysql連接數(shù)據(jù)庫并將查詢結(jié)果轉(zhuǎn)化為Pandas dataframe
- Python pymysql向SQL語句中傳參的多種方法
- python中pymysql的executemany使用方式
- 封裝一個(gè)python的pymysql操作類
- 詳解Python如何利用pymysql封裝項(xiàng)目通用的連接和查詢
- 詳解PyMySQL插入字典類型的數(shù)據(jù)
- python使用pymysql操作MySQL錯(cuò)誤代碼1054和1064處理方式
- python pymysql peewee關(guān)于時(shí)區(qū)問題分析
相關(guān)文章
pandas如何獲取某個(gè)數(shù)據(jù)的行號
這篇文章主要介紹了pandas如何獲取某個(gè)數(shù)據(jù)的行號問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02python獲取當(dāng)前文件路徑以及父文件路徑的方法
今天小編就為大家分享一篇python獲取當(dāng)前文件路徑以及父文件路徑的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07python網(wǎng)絡(luò)爬蟲學(xué)習(xí)筆記(1)
這篇文章主要為大家詳細(xì)介紹了python網(wǎng)絡(luò)爬蟲學(xué)習(xí)筆記的第一篇,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04Django contrib auth authenticate函數(shù)源碼解析
這篇文章主要介紹了Django contrib auth authenticate函數(shù)源碼解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11