溫馨提示×

SQLite怎么查詢表名并刪除表

小億
188
2024-01-05 22:01:29
欄目: 云計算

在SQLite中,可以使用以下語句查詢表名:

SELECT name FROM sqlite_master WHERE type = 'table';

這將返回數(shù)據(jù)庫中所有表的名稱。

要刪除表,可以使用以下語句:

DROP TABLE table_name;

其中,table_name是要刪除的表的名稱。請注意,刪除表將永久刪除表及其內(nèi)容,所以在執(zhí)行此操作前請謹慎。

以下是一個完整的例子,演示如何查詢表名并刪除表:

import sqlite3

# 連接到SQLite數(shù)據(jù)庫
conn = sqlite3.connect('database.db')

# 創(chuàng)建一個游標對象
cursor = conn.cursor()

# 查詢表名
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
print("Tables:")
for table in tables:
    print(table[0])

# 刪除表
table_name = 'table_to_delete'
cursor.execute(f"DROP TABLE {table_name};")
print(f"Table '{table_name}' deleted.")

# 提交事務(wù)并關(guān)閉連接
conn.commit()
conn.close()

請?zhí)鎿Qdatabase.db為你的數(shù)據(jù)庫文件名,并將table_to_delete替換為你要刪除的表的名稱。

0