Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python으로 MySQL 데이터베이스와 서버의 모든 테이블 목록 조회하기

데이터베이스 작업을 하다 보면 해당 데이터베이스나 서버에 존재하는 모든 테이블의 목록을 확인해야 하는 경우가 종종 있습니다. 이럴 때 SHOW TABLES 명령어를 활용하면 간단하게 해결할 수 있습니다.

SHOW TABLES 명령어는 데이터베이스 내부의 테이블 이름뿐만 아니라 서버 전체의 테이블 이름도 조회할 수 있는 유용한 SQL 구문입니다.

기본 문법

데이터베이스 내 테이블 조회

SHOW TABLES

위 구문을 커서(cursor) 객체로 실행하면 현재 연결된 데이터베이스에 존재하는 테이블 이름들이 반환됩니다.

서버 전체 테이블 조회

SELECT table_name FROM information_schema.tables

서버에 존재하는 모든 테이블을 조회하려면 information_schema의 tables 테이블을 참조하면 됩니다.

Python에서 MySQL 테이블 목록을 조회하는 단계

  • MySQL 커넥터(mysql.connector)를 임포트합니다.
  • connect() 메서드를 사용하여 데이터베이스와 연결을 설정합니다.
  • cursor() 메서드로 커서 객체를 생성합니다.
  • 적절한 SQL 구문으로 쿼리를 작성합니다.
  • execute() 메서드를 사용하여 SQL 쿼리를 실행합니다.
  • 작업이 끝나면 연결을 종료합니다.

데이터베이스 내 테이블 조회 예제

import mysql.connector

db = mysql.connector.connect(host="your host", user="your username", password="your_password", database="database_name")

cursor = db.cursor()

cursor.execute("SHOW TABLES")

for table_name in cursor:
    print(table_name)

서버 전체 테이블 조회 예제

import mysql.connector

db = mysql.connector.connect(host="your host", user="your username", password="your_password", database="database_name")

cursor = db.cursor()

cursor.execute("SELECT table_name FROM information_schema.tables")

for table_name in cursor:
    print(table_name)

위 코드를 실행하면 연결된 데이터베이스 또는 서버에 존재하는 테이블 목록이 출력됩니다.

실행 결과

Employees
Students
MyTable