要遍歷PostgreSQL數據庫中的所有用戶表,可以按照以下步驟操作:
- 安裝必要依賴庫
pip install psycopg2-binary
- 使用標準SQL查詢方案(推薦)
import psycopg2def list_user_tables():try:conn = psycopg2.connect(host="your_host",database="your_db",user="your_user",password="your_password")cursor = conn.cursor()# 查詢非系統模式中的用戶表query = """SELECT table_schema, table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE'AND table_schema NOT IN ('information_schema', 'pg_catalog')"""cursor.execute(query)tables = cursor.fetchall()print("用戶表列表:")for schema, table in tables:print(f"Schema: {schema}, Table: {table}")except Exception as e:print(f"數據庫操作異常: {e}")finally:if 'conn' in locals():conn.close()list_user_tables()
- 替代方案(使用pg_catalog)
# 連接代碼同上,替換查詢語句為:
query = """SELECT schemaname, tablename FROM pg_catalog.pg_tables WHERE schemaname NOT LIKE 'pg_%' AND schemaname != 'information_schema'
"""
需要注意:
- 替換連接參數中的占位符為實際值
- 結果包含所有非系統模式中的表(如public模式)
- 查詢結果格式為(模式名,表名)的元組列表
- 需確保數據庫用戶有訪問元數據的權限
建議優先使用information_schema方案,因其符合SQL標準且具有更好的跨數據庫兼容性。