python查詢MySQL數據庫的表以及所有字段


#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymysql

# 查詢所有字段
def list_col(localhost, username, password, database, tabls_name):
    db = pymysql.connect(localhost, username, password, database, charset="utf8")
    cursor = db.cursor()
    cursor.execute("select * from %s" % tabls_name)
    col_name_list = [tuple[0] for tuple in cursor.description]
    db.close()
    return col_name_list

# 列出所有的表
def list_table(localhost, username, password, database):
    db = pymysql.connect(localhost, username, password, database, charset="utf8")
    cursor = db.cursor()
    cursor.execute("show tables")
    table_list = [tuple[0] for tuple in cursor.fetchall()]
    db.close()
    return table_list


username = "root" # 用戶名
password = "root" # 連接密碼
localhost = "localhost" # 連接地址
database = "school" # 數據庫名
tables = list_table(localhost, username, password, database) # 獲取所有表,返回的是一個可迭代對象
print(tables) 

for table in tables:
    col_names = list_col(localhost, username, password, database, table)
    print(col_names) # 輸出所有字段名

來源:Python:查詢 mysql 的所有表和字段 -> pymysql 演示

版權聲明:文章為CSDN博主「顯魄-Simple」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_33811662/article/details/80855430


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM