在 PostgreSQL 中列出所有数据库
本文介绍了在 PostgreSQL 列出数据库的两种方法。
PostgreSQL 提供了两种方法列出 PostgreSQL 服务器中的所有数据库:
- 在
psql工具中使用\l或者\l+列出所有的数据库。 - 从
pg_database表中查询所有的数据库。
使用 \l 列出数据库
本实例演示了使用 psql 工具登录数据库并列出数据库的步骤。请按照如下步骤进行:
-
使用 postgres 用户登录 PostgreSQL 服务器:
[~] psql -U postgres psql (14.4) Type "help" for help.注意:您也可以使用其他任何具有相应的数据库权限的用户登录。
-
使用
\l命令列出所有的数据库,如下:\lList of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+---------+---------+----------------------- postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 | template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres testdb | postgres | UTF8 | C.UTF-8 | C.UTF-8 | testdb2 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | (5 rows) -
如果要查看更多关于数据库的信息,请使用
\l+命令,如下:\l+List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges | Size | Tablespace | Description -----------+----------+----------+---------+---------+-----------------------+---------+------------+-------------------------------------------- postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | 8529 kB | pg_default | default administrative connection database template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +| 8377 kB | pg_default | unmodifiable empty database | | | | | postgres=CTc/postgres | | | template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +| 8529 kB | pg_default | default template for new databases | | | | | postgres=CTc/postgres | | | testdb | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | 8897 kB | pg_default | testdb2 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | 8545 kB | pg_default | (5 rows)
您可以看到, \l+ 的输出比 \l 多了 Size, Tablespace 和 Description 列。
从 pg_database 表中查询数据库
除了上面的 \l+ 和 \l 命令,您还可以从 pg_database 表中查询所有的数据库。
pg_database 表是 PostgreSQL 内置的一个表,它存储了所有的数据库。
SELECT datname FROM pg_database;
datname
-----------
postgres
testdb
template1
template0
testdb2
(5 rows)结论
PostgreSQL 提供了两种方法列出 PostgreSQL 服务器中的所有的数据库中:
- 在
psql工具中使用\l或者\l+列出当所有的数据库。 - 从
pg_database表中查询所有的数据库。
在 MySQL 中,您可以使用 SHOW DATABASES 命令列出数据库。