PythonでATTACHコマンドを使って開いたSQLiteデータベースのテーブル一覧を表示する
SQLiteデータベースファイルでATTACHコマンドを使って開いたテーブル一覧を表示する方法
SQLiteデータベースファイルを開いた後、ATTACHコマンドを使って別のデータベースファイルを接続すると、複数のデータベースをまとめて操作できます。この場合、接続されたデータベースのテーブル一覧を表示する方法について解説します。
手順
以下の手順で、ATTACHコマンドを使って開いたデータベースのテーブル一覧を表示できます。
- SQLiteデータベースファイルを開く
sqlite3 database.sqlite
- ATTACHコマンドを使って別のデータベースファイルを接続する
ATTACH DATABASE 'another_database.sqlite' AS another;
- 接続されたデータベースのテーブル一覧を表示する
.tables another;
コマンド解説
sqlite3 database.sqlite
: 指定された名前のデータベースファイルを開きます。ATTACH DATABASE 'another_database.sqlite' AS another
:another_database.sqlite
という名前のデータベースファイルをanother
というエイリアスで接続します。.tables another
:another
というエイリアスで接続されたデータベースのテーブル一覧を表示します。
例
以下の例では、database.sqlite
というデータベースファイルを開き、another_database.sqlite
というデータベースファイルを another
というエイリアスで接続した後、接続されたデータベースのテーブル一覧を表示しています。
sqlite3 database.sqlite
ATTACH DATABASE 'another_database.sqlite' AS another;
.tables another;
# 出力例
#
# テーブル名
# --------
# customers
# orders
# products
補足
.tables
コマンドは、接続されているすべてのデータベースのテーブル一覧を表示することもできます。この場合、エイリアスは不要です。
.tables
- 特定のデータベースのテーブル一覧を表示するには、
LIKE
演算子を使用できます。
.tables LIKE 'another%';
# 出力例
#
# テーブル名
# --------
# another_customers
# another_orders
# another_products
import sqlite3
# データベースファイルを開く
connection = sqlite3.connect("database.sqlite")
# 別のデータベースファイルを接続する
cursor = connection.cursor()
cursor.execute("ATTACH DATABASE 'another_database.sqlite' AS another")
# 接続されたデータベースのテーブル一覧を表示する
cursor.execute(".tables another")
for table in cursor.fetchall():
print(table[0])
# 接続を閉じる
connection.close()
このコードを実行すると、another_database.sqlite
データベース内のテーブル名がコンソールに出力されます。
実行例
$ python sample.py
customers
orders
products
他の方法
PRAGMA table_listコマンドを使う
PRAGMA table_list;
このコマンドは、接続されているすべてのデータベースのテーブル一覧を表示します。
SELECT name FROM sqlite_master WHERE type='table'クエリを使う
SELECT name FROM sqlite_master WHERE type='table';
Pythonのsqlite3モジュールを使う
import sqlite3
# データベースファイルを開く
connection = sqlite3.connect("database.sqlite")
# 接続されたデータベースのテーブル一覧を取得する
cursor = connection.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [table[0] for table in cursor.fetchall()]
# 接続を閉じる
connection.close()
# テーブル名を出力する
for table in tables:
print(table)
このコードは、Pythonのsqlite3モジュールを使って、接続されているすべてのデータベースのテーブル名を取得し、出力します。
- 接続されたデータベースのテーブル一覧をすべて表示したい場合は、
PRAGMA table_list
コマンドを使うのが簡単です。 - Pythonスクリプトからテーブル一覧を取得したい場合は、Pythonのsqlite3モジュールを使うのが便利です。
sql sqlite database-schema