如何使用Python和MySQLdb检索mysql数据库中的表名?

问题描述 投票:0回答:5

我有一个 SQL 数据库,想知道您使用什么命令来获取该数据库中的表名称列表。

python mysql mysql-python
5个回答
86
投票

更完整一点:

import MySQLdb

connection = MySQLdb.connect(
                host = 'localhost',
                user = 'myself',
                passwd = 'mysecret')  # create the connection

cursor = connection.cursor()     # get the cursor


cursor.execute("USE mydatabase") # select the database

cursor.execute("SHOW TABLES")    # execute 'SHOW TABLES' (but data is not returned)

现在有两个选择:

tables = cursor.fetchall()       # return data from last query

或迭代光标:

 for (table_name,) in cursor:
        print(table_name)

10
投票

显示表格

15 个字符


7
投票

show tables
会有所帮助。 这是文档


4
投票

还可以通过使用下面的驱动程序执行单个查询来从特定方案获取表。

python3 -m pip install PyMySQL
import pymysql

# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='my_database')

# Create a Cursor object
cur = conn.cursor()

# Execute the query: To get the name of the tables from a specific database
# replace only the my_database with the name of your database
cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'my_database'")

# Read and print tables
for table in [tables[0] for tables in cur.fetchall()]:
    print(table)

输出:

my_table_name_1
my_table_name_2
my_table_name_3
...
my_table_name_x

0
投票

这是使用

sqlalchemy
pandas
库的另一个答案

from sqlalchemy import create_engine
import pandas as pd

# Make connection to server
def connect(self):  
    # create sqlalchemy engine
    engine = create_engine("mysql+pymysql://{user}:{pw}@{server}/{db}"
            .format(user=self.username,
            pw=self.password,
            server=self.server,
            db=self.database))
    return engine   

if _name_ == '_main_':
    server = 'myserver'
    database = 'mydatabase'
    username = 'myusername'
    password = 'mypassword'
    table = 'mytable'

    con = connect()
    my_query = f"SHOW COLUMNS FROM {table};"
    df = pd.read_sql_query(sql=my_query, con=con)

© www.soinside.com 2019 - 2024. All rights reserved.