如何在Python中列出PostgreSQL数据库并将名称存入列表
在Python中获取PostgreSQL数据库名称并存入列表的实现方法
步骤1:安装依赖库
PostgreSQL的Python适配库推荐用psycopg2-binary,它是预编译版本,无需处理编译依赖:
pip install psycopg2-binary
步骤2:编写实现代码
通过连接PostgreSQL默认的postgres库(或其他已存在的库),查询系统表pg_database获取非模板数据库名称,最终转为列表:
import psycopg2 def get_postgres_dbs(): # 替换为你的实际连接参数 conn_params = { "host": "localhost", "user": "your_username", "password": "your_password", "database": "postgres" } db_list = [] conn = None try: # 建立连接 conn = psycopg2.connect(**conn_params) cursor = conn.cursor() # 查询所有非模板数据库 cursor.execute("SELECT datname FROM pg_database WHERE datistemplate = false;") # 转换为字符串列表 db_list = [row[0] for row in cursor.fetchall()] except psycopg2.DatabaseError as e: print(f"数据库操作出错: {e}") finally: # 释放资源 if conn: cursor.close() conn.close() return db_list # 调用函数获取结果 databases = get_postgres_dbs() print("PostgreSQL数据库列表:", databases)
关键说明
- 必须连接到一个已存在的数据库才能查询系统表,默认的
postgres库是最稳妥的选择 pg_database是PostgreSQL的系统目录表,存储所有数据库的元数据datistemplate = false会过滤掉PostgreSQL自带的模板数据库(template0、template1),只返回用户创建的数据库
内容的提问来源于stack exchange,提问作者Shakalll
相关产品推荐
相关产品推荐

