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

发布于 2024-09-15 22:30:29 字数 44 浏览 5 评论 0原文

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

I have an SQL database and am wondering what command you use to just get a list of the table names within that database.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

橪书 2024-09-22 22:30:29

更完整一点:

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)

To be a bit more complete:

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)

now there are two options:

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

or iterate over the cursor:

 for (table_name,) in cursor:
        print(table_name)
风月客 2024-09-22 22:30:29

显示表

15 个字符

SHOW tables

15 chars

显示表格会有所帮助。 这里是文档

show tables will help. Here is the documentation.

奶气 2024-09-22 22:30:29

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

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

It is also possible to obtain tables from a specific scheme with execute the single query with the driver below.

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)

output:

my_table_name_1
my_table_name_2
my_table_name_3
...
my_table_name_x
長街聽風 2024-09-22 22:30:29

这是使用 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)

Here is another answer using the sqlalchemy and pandas libraries

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文