programing

Python 및 MySQLDB를 사용하여 mysql 데이터베이스에서 테이블 이름을 검색하는 방법은 무엇입니까?

cafebook 2023. 9. 5. 20:46
반응형

Python 및 MySQLDB를 사용하여 mysql 데이터베이스에서 테이블 이름을 검색하는 방법은 무엇입니까?

SQL 데이터베이스가 있는데 해당 데이터베이스 내의 테이블 이름 목록을 가져오는 데 어떤 명령을 사용하는지 궁금합니다.

좀 더 완벽하게 하기 위해서는:

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)

표 표시

15챠

show tables도움이 될 것입니다.여기 설명서가 있습니다.

아래 드라이버를 사용하여 단일 쿼리를 실행하여 특정 스킴에서 테이블을 가져올 수도 있습니다.

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

언급URL : https://stackoverflow.com/questions/3556305/how-to-retrieve-table-names-in-a-mysql-database-with-python-and-mysqldb

반응형