Python:读取PostgreSQL表的关系(外键表)

时间:2017-02-15 11:18:07

标签: python postgresql

我需要使用python阅读postgres数据库模式。我已经可以使用

读取表名和列名
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]

我也希望阅读表格之间的关系。有谁知道怎么做?

1 个答案:

答案 0 :(得分:-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 +'""")