test_connent_pgsql.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # -*- coding: utf-8 -*-
  2. import psycopg2
  3. # PostgreSQL数据库连接参数
  4. host = "192.168.100.122:20788"
  5. dbname = "postgres"
  6. user = "freshrss"
  7. password = "freshrss"
  8. # 连接到PostgreSQL数据库
  9. conn = psycopg2.connect(host=host, dbname=dbname, user=user, password=password)
  10. conn.autocommit = True
  11. # 创建一个cursor对象
  12. cur = conn.cursor()
  13. # 获取所有数据库的名称
  14. cur.execute("SELECT datname FROM pg_database WHERE datistemplate = false;")
  15. databases = cur.fetchall()
  16. print("数据库列表:")
  17. for db in databases:
  18. print(db[0])
  19. # 连接到具体的数据库
  20. conn.close()
  21. conn = psycopg2.connect(dbname=db[0], user=user, password=password, host=host)
  22. cur = conn.cursor()
  23. # 获取该数据库中的所有表
  24. cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema='public';")
  25. tables = cur.fetchall()
  26. print(f"\n数据库 '{db[0]}' 的表列表:")
  27. for table in tables:
  28. print(table[0])
  29. # 关闭cursor和连接
  30. cur.close()
  31. conn.close()