[英]Python SQLite getting names of the tables that contain columns with specific name
有一個包含多個表的數據庫。 有沒有辦法打印出包含與客戶相關的列的表名,例如:customer_ID?
我需要做的是:有兩個名為“payment”和“customer”的表,其中包含“customer_ID”列,因此必須打印“payment”和“customer”表的名稱。
您可以將exists
與子查詢一起使用:
select m.name from sqlite_master m where m.type = 'table' and exists
(select 1 from pragma_table_info(m.name) m1 where m1.name = 'customer_ID')
import sqlite3
conn = sqlite3.connect('test_db.db')
r = list(conn.cursor().execute('''select m.name from sqlite_master m where m.type = 'table' and exists
(select 1 from pragma_table_info(m.name) m1 where m1.name = 'customer_ID')'''))
這是一個自定義生成器 function 以獲取包含至少一個給定列名的表:
def getTableNames(path, cols):
con = sqlite3.connect(path)
for (tableName, ) in con.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
if any(col for col in [fields[1] for fields in con.execute(f"PRAGMA table_info({tableName})").fetchall()] if
col in cols):
yield tableName
然后調用:
>>> list(getTableNames(path, ['customer_ID']))
這個想法是首先獲取表的列表,然后獲取 sqlite 中存在的任何表的所有列,然后從給定的列列表中過濾掉包含任何列的表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.