如何在 Python 中列出 SQLite3 数据库中的表
你可以使用此代码片段在 Python 中列出 SQLite 3.x 数据库中的所有 SQL 表:
list_tables.py
def tables_in_sqlite_db(conn):
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [
v[0] for v in cursor.fetchall()
if v[0] != "sqlite_sequence"
]
cursor.close()
return tables用法示例:
usage_example.py
#!/usr/bin/env python3
import sqlite3
# 打开数据库
conn = sqlite3.connect('/usr/share/command-not-found/commands.db')
# 列出表
tables = tables_in_sqlite_db(conn)
# 你的代码放在这里!
# 示例:
print(tables) # 打印 ['commands', 'packages']If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow