2017-02-15 50 views
1

我需要使用python讀取postgres數據庫模式。我可以使用,Python:讀取PostgreSQL的關係(外鍵表)表

cursor.execute(
    "select relname 
    from pg_class 
    where relkind='r' and relname !~ '^(pg_|sql_)';") 

,並

cursor.execute("Select * FROM " + table_name) 
colnames = [desc[0] for desc in cursor.description] 

我想讀表之間的關係,以及已經讀表和列名。有誰知道如何做到這一點?

+0

我會用'information_schema.key_column_usage'和'information_schema.table_constraints'開始。特別注意列「constraint_schema」和「table_schema」。您可以在多個模式中使用相同的表名。 –

回答

-1

請嘗試使用此查詢它應該很好地工作:

cursor.execute("""SELECT 
    tc.constraint_name, tc.table_name, kcu.column_name, 
    ccu.table_name AS foreign_table_name, 
    ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu 
     ON tc.constraint_name = kcu.constraint_name 
    JOIN information_schema.constraint_column_usage AS ccu 
     ON ccu.constraint_name = tc.constraint_name 
WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='+ table_name +'""")