我需要使用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]
我也希望阅读表格之间的关系。有谁知道怎么做?
答案 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 +'""")