How can you query table names and delete tables in SQLite?

You can use the following statement in SQLite to query the table name:

SELECT name FROM sqlite_master WHERE type = 'table';

This will return the names of all tables in the database.

To delete a table, you can use the following statement:

DROP TABLE table_name;

Please note that deleting the table will permanently remove the table and its contents, so please proceed with caution before executing this operation.

Here is a complete example showcasing how to query table names and delete tables.

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('database.db')

# 创建一个游标对象
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.")

# 提交事务并关闭连接
conn.commit()
conn.close()

Please replace database.db with the name of your database file, and replace table_to_delete with the name of the table you want to delete.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds